Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: n ≤ 2·10⁵ meetings [s, e); choose the maximum number of non-overlapping ones. Compare three greedy orders: by end time, by start time, by length.

Problem: n ≤ 2·10⁵ meetings [s, e); choose the maximum number of non-overlapping ones. Compare three greedy orders: by end time, by start time, by length.
def by_end(iv):
    cnt, end = 0, float("-inf")
    for s, e in sorted(iv, key=lambda x: x[1]):
        if s >= end: cnt += 1; end = e
    return cnt
def by_start(iv):
    cnt, end = 0, float("-inf")
    for s, e in sorted(iv):
        if s >= end: cnt += 1; end = e
    return cnt
def by_len(iv):
    chosen = []
    for s, e in sorted(iv, key=lambda x: x[1] - x[0]):
        if all(e <= cs or s >= ce for cs, ce in chosen): chosen.append((s, e))
    return len(chosen)
A = [(0, 10), (1, 3), (4, 6), (7, 9)]
B = [(0, 4), (3, 6), (5, 9)]
print(by_end(A), by_start(A), by_len(A), by_end(B), by_start(B), by_len(B))
What is printed?
  1. A. 3 1 3 2 2 1
  2. B. 3 1 1 2 2 1
  3. C. 3 1 3 2 1 1
  4. D. 3 3 3 2 2 2

Correct answer: A. 3 1 3 2 2 1

Earliest end time is provably optimal (exchange argument) and runs in O(n log n). Earliest start fails on A: it takes (0, 10) and blocks the three short meetings. Shortest first fails on B: it takes (3, 6), which overlaps both (0, 4) and (5, 9), leaving 1 instead of 2. by_len is also O(n²) as written. So only 'sort by end' passes all tests at n = 2·10⁵.

More Coding Interview Problems questions

Exams that ask this topic