Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Asteroids move along a line: positive = right, negative = left, |value| = size. When two meet, the smaller explodes; equal sizes both explode.

Problem: Asteroids move along a line: positive = right, negative = left, |value| = size. When two meet, the smaller explodes; equal sizes both explode.
def collide(a):
    st = []
    for x in a:
        alive = True
        while alive and x < 0 and st and st[-1] > 0:
            if st[-1] < -x: st.pop()
            elif st[-1] == -x: st.pop(); alive = False
            else: alive = False
        if alive: st.append(x)
    return st
print(collide([8, -8, 3, -2, -6, 4]))
What is printed?
  1. A. [3, 4]
  2. B. [-8, 3, 4]
  3. C. [-6, 4]
  4. D. [4]

Correct answer: C. [-6, 4]

8 and −8 destroy each other. 3 beats −2, then −6 destroys 3 and, with nothing moving right left on the stack, flies on. The final 4 moves right, away from −6, so they never meet.

More Coding Interview Problems questions

Exams that ask this topic