Google Online Challenge - Technical Question for Technical Solution Engineer - Solved!
Question:
Please have a look at the following pseudo-code. Please note that syntax may be completely different from any programming languages you know, More specifically, Indentation does not matter in the code, ":=" denotes the substitution, and "=" is the comparator
A is a 2D array which has the size 4x4;
Initial State of A array :
[2, NULL,2, NULL],[2, NULL,2, NULL],
[NULL,NULL,NULL,NULL],
[NULL,NULL,NULL,NULL]]
FOR y = 0 to 3
FOR x = 0 to 3
IF a[x+1][y] != NULL
IF a[x+1][y] = a[x][y]:
a[x][y] := a[x][y]*2
a[x+1][y] := NULL
END IF
IF a[x][y] = NULL
a[x][y] := a[x+1][y]
a[x+1][y] := NULL
END IF
END IF
END FOR
END FOR
END FUNCTION
[NULL,NULL,NULL,NULL],
[NULL,NULL,NULL,NULL]]
Main Function:
FUNCTION foo()FOR y = 0 to 3
FOR x = 0 to 3
IF a[x+1][y] != NULL
IF a[x+1][y] = a[x][y]:
a[x][y] := a[x][y]*2
a[x+1][y] := NULL
END IF
IF a[x][y] = NULL
a[x][y] := a[x+1][y]
a[x+1][y] := NULL
END IF
END IF
END FOR
END FOR
END FUNCTION
what is the biggest problem with the above code and how would you fix it?
- It will file at runtime because of an attempt to access a non-existing object. Memory location or array index. This can be fixed by. changing the limits of the FOR loops.
- Some NULL checks or missing for numeric operations which could lead to undefined behaviour.
- Integers can't ever be NULL so it's not possible to mix these in an array. This can be addressed by replacing the 2's in the initial state with strings. Example "2".
- The code does 'work' in that It will manipulate the away. All that's wrong is that there is no specification for what it should do.
- The Foo() function should declare that it throws an exception.
- The second IF statement can never be called.It can safely remove from the code.
Solution:
- It will file at runtime because of an attempt to access a non-existing object. Memory location or array index. This can be fixed by. changing the limits of the FOR loops.
Explanation:
At the third iteration of the Outer FOR loop cause, an array bound exception which attempts to access a non-existing object or memory location.
Code runs smoothly until the 3 iterations begins.
At the 3 Iteration ==> if(a[4][0) != NULL) this will cause an error.
'A' array - 4x4 which is
[a[0][0] ,a[0][1],a[0][2],a[0][3]],
[a[1][0] a[1][1] a[1][2] a[1][3]],
[a[2][0],a[2][1],a[2][2],a[2][3]],
[a[3][0],a[3][1],a[3][2],a[3][3]]
There is no such element in 'A' like- A[4][0].
So, By fixing the FOR limits, the code runs successfully.
Please read this article to find more interesting for the following question: Microsoft technical interview: Matrix Algorithm - Stack Overflow

2 Comments
Thanks alot for this!
ReplyDeleteThanks! Kindly sharing it with your friends!
ReplyDelete