Data Structures & AlgorithmsVery hardGATE CS · DSA
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([8, -2, -8, 4, -6, -9, -4, -8]))- A. [−6, −9, −8, −4]
- B. [−6, −4, −9, −8]
- C. [−9, −4, −8]
- D. [−6, −9, −4, −8]
Correct answer: D. [−6, −9, −4, −8]
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, −4, −8].
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Lines of heights [9, 5, 3, 2, 4, 9, 1, 2, 9] stand at x = 0, 1, …, 8. Two pointers find the pair of lines that, with the x-axis, holds the…
- How many different pop sequences are possible when 6 distinct items are pushed onto a stack in a fixed order, with pops allowed at any time?
- Count zero-sum contiguous subarrays with a prefix-sum frequency map. What is printed? python from collections import defaultdict a = [1…
- Daily prices are [26, 31, 28, 30, 24, 30, 18, 37, 13]. What is the maximum profit with at most ONE buy and one later sell, and with…
- Floyd's cycle detection on a list whose last node links back into the list. What does this print (meeting value, cycle-start value, cycle…
- One Lomuto partition (pivot = LAST element; i marks the end of the 'less than pivot' region; when a[j] < pivot, increment i and swap a[i]…