Data Structures & AlgorithmsHardProduct Company SDE · interval cover
Problem: What is the minimum number of intervals from [[1,4],[3,7],[6,10],[9,10]] needed to cover the segment [1, 10]? Run the greedy code.
Problem: What is the minimum number of intervals from [[1,4],[3,7],[6,10],[9,10]] needed to cover the segment [1, 10]? Run the greedy code.
iv = [(1, 4), (3, 7), (6, 10), (9, 10)]
start, end = 1, 10
cur = start
cnt = 0
while cur < end:
best = max((e for s, e in iv if s <= cur), default=None)
if best is None or best <= cur:
cnt = -1
break
cur = best
cnt += 1
print(cnt)What is printed?- A. 2
- B. 3
- C. 4
- D. -1
Correct answer: B. 3
Starting at 1, the best reach is 4, then 7 from [3,7], then 10 from [6,10], so three intervals are needed.
More Coding Interview Problems questions
- Problem: How many pairs (i < j) of [1, 2, 3, 4, 5] have a[i] XOR a[j] = 1? Run the code. python a = [1, 2, 3, 4, 5] print(sum(1 for i in…
- Problem: How many subarrays of [3, 4, 7, 2, -3, 1, 4, 2] have sum exactly 7? Run the prefix-sum hash code. python from collections import…
- Problem: What is the length of the shortest substring of 'aabcbcdbca' that contains all distinct characters of the string? Run the…
- Problem: What is the Levenshtein distance between 'horse' and 'ros'? Run the DP. python a, b = 'horse', 'ros' dp = [[0] (len(b) + 1) for…
- Problem: What is the sum of |ai - aj| over all pairs i < j of the sorted array [1, 4, 6]? Run the code. python a = sorted([1, 4, 6])…
- Problem: Which complexity does the sieve of Eratosthenes have for finding all primes up to n?