Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Asteroids move along a line: positive = right, negative = left, |value| = size. When two meet, the smaller explodes; equal sizes both explode.
Problem: Asteroids move along a line: positive = right, negative = left, |value| = size. When two meet, 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([8, -8, 3, -2, -6, 4]))What is printed?- A. [3, 4]
- B. [-8, 3, 4]
- C. [-6, 4]
- D. [4]
Correct answer: C. [-6, 4]
8 and −8 destroy each other. 3 beats −2, then −6 destroys 3 and, with nothing moving right left on the stack, flies on. The final 4 moves right, away from −6, so they never meet.
More Coding Interview Problems questions
- Problem: Decode a string where k[s] means s repeated k times (brackets can nest). python def decode(s): st, cur, k = [], "", 0 for c in s…
- Problem: Evaluate an expression with +, −, parentheses and non-negative integers, using a stack of signs. python def calc(s): res, num…
- Problem: Remove duplicate letters so that each letter appears once and the result is the lexicographically smallest possible subsequence…
- Problem: Report the running median of a stream using a max-heap (lower half) and a min-heap (upper half). python import heapq def…
- Which statement about selecting the k-th smallest of n unsorted numbers is correct?
- Problem: Find the smallest divisor d such that Σ ceil(a[i] / d) ≤ threshold. python def smallestdiv(a, t): lo, hi = 1, max(a) while lo <…