Data Structures & AlgorithmsVery hardTCS Digital · Infosys SP

Asteroids move along a line: positive values move right, negative move left; on collision the smaller (by absolute value) explodes, equal sizes both explode. What survives?

Asteroids move along a line: positive values move right, negative move left; on collision the smaller (by absolute value) explodes, equal sizes both explode. What survives?
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([-3, -2, 2, 5, -9, -8, 6, 3]))
  1. A. []
  2. B. [−3, −2, −8, −9, 6, 3]
  3. C. [−3, −2, −9, −8, 6, 3]
  4. D. [−2, −3, −9, −8, 6, 3]

Correct answer: C. [−3, −2, −9, −8, 6, 3]

Only a left-mover meeting a right-mover on the stack's top can collide; two left-movers or a left-mover followed by a right-mover never meet. Result: [−3, −2, −9, −8, 6, 3].

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic