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?- A. 3 1 3 2 2 1
- B. 3 1 1 2 2 1
- C. 3 1 3 2 1 1
- 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
- Problem: A road network has weights 1..5 (n, m ≤ 2·10⁵). A candidate solution runs plain BFS and sets dist[v] = dist[u] + w the first time…
- Problem: Each link succeeds with a probability; find the most reliable path from 0 to 3 (maximise the product). Dijkstra works with a…
- Problem: Board game on squares 1..n: roll a die (1–6); landing on the foot of a ladder or the head of a snake moves you to its other end…
- Problem: Find the bug: Kahn's algorithm is used to schedule build steps, but nobody checks whether a cycle exists. What does it return for…
- Problem: n, q ≤ 2·10⁵ operations of two kinds: add v to every a[l..r], and ask for sum a[l..r]. A Fenwick tree with two arrays supports…
- Problem: For n = 2·10⁵, compute Σ over all subarrays of (max − min). Sum of maxima minus sum of minima, each via monotonic stacks with…