Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Simulate asteroids on a line: positive moves right, negative left; on collision the smaller explodes, equal sizes both explode.

Problem: Simulate asteroids on a line: positive moves right, negative left; on collision 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([5, 10, -5]), collide([8, -8]), collide([10, 2, -5]), collide([-2, -1, 1, 2]))
What is printed?
  1. A. [10] [] [10] [-2, -1, 1, 2]
  2. B. [5, 10] [8] [10] [1, 2]
  3. C. [5, 10] [] [10, -5] [-2, -1, 1, 2]
  4. D. [5, 10] [] [10] [-2, -1, 1, 2]

Correct answer: D. [5, 10] [] [10] [-2, -1, 1, 2]

Only a right-mover on the stack followed by a left-mover collide. −5 dies against 10; 8 and −8 both explode; −5 destroys 2 then dies against 10; in the last case left-movers come first and never meet the right-movers. Each asteroid is pushed and popped at most once: O(n).

More Coding Interview Problems questions

Exams that ask this topic