How to Solve a Problem 2, Diagonal Difference

Someone commented that perhaps the problem I picked last time to illustrate the process was a bit too hard, so here's an "easy" problem. 

Let's do an easy one, "Diagonal Difference" from hackerrank. 

They just want the difference of the two diagonals. That means we should only have to traverse the 2-D array twice, once for each diagonal. 

BONUS: we may be able to do it only ONCE. 

Let's read the problem very carefully. The array can be arbitrarily large, but the values are always between -100 and 100. Nothing special there. 

But the value they want is "int: the absolute diagonal difference". So you need the absolute value of the answer, not the actual value. It's often the details like this that trip people up. 

So how do you get the first difference? With a loop, of course. The first diagonal is slope of 1, or x=y. First item is [0,0], and last item is [length-1,length-1]

So the loop will be:

(this is pseudocode, not valid JavaScript)

diagonalsum1=0

for i from 0 to arr.length-1

    diagonalsum1+=arr[i][i]

endfor

That takes care of diagonal. But what about the OTHER diagonal? This is where you need to make sure you're referring to the proper axis. A lot of people put the negative on the wrong axis. 

If you check the value of [0,1], you will find it's first row, second column. With their sample input of a 3x3, it is "2"

To get the OTHER diagonal, first item is [length-1,0] and last item is [0,length-1]. Slope = -1, x=-y

Do you see the pattern? Y is still 0 to length-1, but X is now length-1 to 0. 

Given that we can use the same loop, we just need a new expression for X, and in this case, it's length-1-i

diagonalsum1=0

diagonalsum2=0

for i from 0 to arr.length-1

    diagonalsum1+=arr[i][i]

    diagonalsum2+=arr[length-1-i][i]

endfor

Don't forget that you need to return the absolute value. 


Comments

Popular posts from this blog

Yet another take on recursion

Problem Solving for Programmers: a Neglected Topic?

How to Solve a Problem, with Examples