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([7, 4, -7, 6, 9, 5, 6, -4]))
  1. A. [9, 6, 5, 6]
  2. B. [6, 9, 5, 6]
  3. C. [6, 5, 9, 6]
  4. D. [7, 6, 9, 5, 6]

Correct answer: B. [6, 9, 5, 6]

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: [6, 9, 5, 6].

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

Exams that ask this topic