Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Given n balloons as horizontal intervals, find the minimum number of vertical arrows that burst all of them (a balloon bursts if the arrow's x is within it, inclusive).
Problem: Given n balloons as horizontal intervals, find the minimum number of vertical arrows that burst all of them (a balloon bursts if the arrow's x is within it, inclusive).
def arrows(b):
b.sort(key=lambda x: x[1])
cnt, pos = 0, float('-inf')
for s, e in b:
if s > pos:
cnt += 1; pos = e
return cnt
print(arrows([[10, 16], [2, 8], [1, 6], [7, 12]]), arrows([[1, 2], [2, 3], [3, 4], [4, 5]]))What is printed?- A. 2 2
- B. 2 4
- C. 3 2
- D. 1 2
Correct answer: A. 2 2
Sort by end and shoot at the end of each balloon not already burst: x = 6 bursts [1,6] and [2,8]; x = 12 bursts [7,12] and [10,16]. Touching counts, so x = 2 bursts [1,2], [2,3] and x = 4 bursts the rest. Using s >= pos would count touching balloons twice (4). O(n log n).
More Coding Interview Problems questions
- Problem: Insert a new interval into a sorted list of non-overlapping intervals, merging if necessary. python def insert(iv, new): out, i…
- Problem: n ≤ 10⁵ trains arrive and depart at given minutes. Find the minimum number of platforms. Which approach is O(n log n) and correct?
- Problem: Assign cookies of sizes s to children with greed factors g (a child is content if cookie ≥ greed). Maximise content children…
- Problem: A staircase has n steps; you climb 1 or 2 steps at a time. Count the distinct ways to reach the top. cpp long long ways(int n) {…
- Problem: A thief robs houses in a row but cannot rob two adjacent houses. Find the maximum loot. python def rob(a): take = skip = 0 for x…
- Problem: Same robbery, but the houses form a circle (first and last are adjacent). python def line(a): take = skip = 0 for x in a: take…