Data Structures & AlgorithmsHardProduct Company SDE · greedy OA
Problem: What is the minimum number of intervals to remove so that the rest are pairwise non-overlapping (touching at an endpoint is allowed)? Run the greedy code on [[1,2],[2,3],[3,4],[1,3]].
Problem: What is the minimum number of intervals to remove so that the rest are pairwise non-overlapping (touching at an endpoint is allowed)? Run the greedy code on [[1,2],[2,3],[3,4],[1,3]].
def rem(iv):
iv = sorted(iv, key=lambda x: x[1])
end = float('-inf')
keep = 0
for s, e in iv:
if s >= end:
keep += 1
end = e
return len(iv) - keep
print(rem([[1, 2], [2, 3], [3, 4], [1, 3]]))What is printed?- A. 0
- B. 2
- C. 1
- D. 3
Correct answer: C. 1
The greedy keeps the intervals by earliest end, keeping [1,2], [2,3] and [3,4] and dropping [1,3]. Sorting by start time instead can drop too many intervals.
More Coding Interview Problems questions
- Problem: The prefix sums of [2, 5, 1, 7, 3] are stored in a list p. What is printed by the code, which finds the first index whose prefix…
- Problem: Arrange the numbers 3, 30, 34, 5, 9 so that the concatenation is the largest possible. Run the code and state the printed string…
- Problem: How many integers x with 1 <= x <= 100 satisfy x^3 ≡ x (mod 7)? python print(sum(1 for x in range(1, 101) if pow(x, 3, 7) == x %…
- Problem: What does the following print? python from math import lcm print(lcm(range(1, 11)))
- Problem: How many integers from 1 to 100 have exactly 3 positive divisors? python print(sum(1 for x in range(1, 101) if sum(1 for d in…
- Problem: Piles of stones are 3, 4 and 5. Two players alternately remove any positive number of stones from one pile, and whoever takes the…