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?- A. [10] [] [10] [-2, -1, 1, 2]
- B. [5, 10] [8] [10] [1, 2]
- C. [5, 10] [] [10, -5] [-2, -1, 1, 2]
- 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
- Problem: Remove k digits from a number string to make the smallest possible number (no leading zeros in the result, "0" if empty). python…
- Problem: Design a stack that returns its minimum in O(1). The implementation below stores pairs. python st = [] def push(x): st.append((x…
- Problem: Return the first index whose value is ≥ x in a sorted array (n if none). cpp int lowerBound(vector<int>& a, int x) { int lo = 0…
- Problem: Count how many times a value occurs in a sorted array in O(log n). python from bisect import bisectleft, bisectright a = [2, 4…
- Problem: Search a target in a sorted array of distinct values that has been rotated at an unknown pivot. python def search(a, t): lo, hi =…
- Problem: Find the minimum of a rotated sorted array of distinct values. python def findmin(a): lo, hi = 0, len(a) - 1 while lo < hi: mid =…