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]))- A. [9, 6, 5, 6]
- B. [6, 9, 5, 6]
- C. [6, 5, 9, 6]
- 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].
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
- 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]…
- Keys 47, 74, 63, 43, 45, 59, 85 are inserted in this order into an empty table of size 13 using quadratic probing: probe i goes to (k mod…
- What does this loop-counting code print? (Python) python n, c = 300, 0 i = 2 while i <= n: c += 1 i = i i print(c)
- Integer square root by binary search (largest m with m·m ≤ n). What is printed (root, iterations)? python n, lo, hi, it = 1000, 0, 1000, 0…
- A mountain is a contiguous subarray of length ≥ 3 that strictly increases to a single peak and then strictly decreases. What is the length…
- How many inversions (pairs i < j with a[i] > a[j]) does [38, 33, 1, 17, 31, 28, 18, 35] have? (This is also the number of swaps bubble…