Data Structures & AlgorithmsHardProduct Company SDE · ICPC regional
Intervals (start, end) are compatible when one ends at or before the other starts. Run the earliest-finish greedy on the list below and report how many intervals it keeps.
Intervals (start, end) are compatible when one ends at or before the other starts. Run the earliest-finish greedy on the list below and report how many intervals it keeps.
iv=[(1,4),(3,5),(0,6),(5,7),(3,9),(5,9),(6,10),(8,11),(8,12),(2,14),(12,16)]
c=0; e=-1
for s,t in sorted(iv,key=lambda x:x[1]):
if s>=e: c+=1; e=t
print(c)What number does it print?- A. 3
- B. 4
- C. 1
- D. 11
Correct answer: B. 4
Earliest-finish greedy is optimal for interval scheduling. Sorting by start can pick a long interval that blocks two short ones, sorting by start descending is a nonsense order, and forgetting to update the boundary after taking an interval lets every interval through.
More Coding Interview Problems questions
- Coins of denominations 1, 3 and 4 are available with unlimited supply. For the amount 6, run the DP that finds the minimum number of coins…
- Array a = [1, 3, 2, 3, 1, 4, 5, 2]. Subsequences are chosen by index (positions may repeat values). Count the strictly increasing…
- Two strings are "intention" and "execution". Compute the minimum cost to turn the first into the second, where insertion and deletion cost…
- A staircase is climbed with steps of size 1, 3 or 4 (order of steps matters). How many distinct ordered sequences of steps reach exactly…
- Forty-one people stand in a circle numbered 1 to 41. Starting from person 1, every third person is removed, repeatedly, counting continues…
- Compute the sum of the prefix-function (KMP failure) array of the string "abacabab", where pi[i] is the length of the longest proper…