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?
  1. A. 2 2
  2. B. 2 4
  3. C. 3 2
  4. 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

Exams that ask this topic