Amazon Interview Question
Principal Software EngineersCountry: India
Interview Type: Phone Interview
Treating the x dimension separately from the y dimension is a nice touch here. For any interview problem in 2D or 3D, a good think to ask yourself is whether you can treat the movements in the different dimensions as being independent. If you can treat the dimensions as being independent, then you basically can reduce the problem to a 1D problem.
@kkr.ashish
How do you decide by what number to divide ? Like you used %4. For x it seems fine, as you start with x=4, and we are trying to get x relative to it. But for y also you have %4. Could you elaborate a bit...I guess I'm missing why you take (i-1)%4...
Because after reading your algo description I figured that in x you should take min(x) and max(x). Similarly for y you should get min(y) and max(y). Multiply difference between min-max x and min-max y
Thanks
Here is a Python solution.
def compute_spiral_area(movements):
i = 0
max_x = 0
min_x = 0
max_y = 0
min_y = 0
x = 0
y = 0
while True:
if i >= len(movements): break
x += movements[i]
if x > max_x: max_x = x
i += 1
if i >= len(movements): break
y += movements[i]
if y > max_y: max_y = y
i += 1
if i >= len(movements): break
x -= movements[i]
if x < min_x: min_x = x
i += 1
if i >= len(movements): break
y -= movements[i]
if y < min_y: min_y = y
i += 1
return (max_x - min_x) * (max_y - min_y)
input = [4,3,5,4,10]
print compute_spiral_area(input)
35 sq units for the sample.
Find the min y and max y
Find min x and max x
Rectangle will be composed of two diagonally apposite points (min x, min y) and <max x, max y).
Length =max x - min x
Height = max y - min y
with the given sample...it is
Length=4 - (-1) = 5
Height=7-0=7 (assume x,y initial position as 0,0)
35=7*5