Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: Insert a new interval into a sorted list of non-overlapping intervals, merging if necessary.
Problem: Insert a new interval into a sorted list of non-overlapping intervals, merging if necessary.
def insert(iv, new):
out, i, n = [], 0, len(iv)
while i < n and iv[i][1] < new[0]:
out.append(iv[i]); i += 1
while i < n and iv[i][0] <= new[1]:
new = [min(new[0], iv[i][0]), max(new[1], iv[i][1])]; i += 1
return out + [new] + iv[i:]
print(insert([[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], [4, 8]))What is printed?- A. [[1, 2], [3, 8], [12, 16]]
- B. [[1, 2], [3, 10], [12, 16]]
- C. [[1, 2], [4, 10], [12, 16]]
- D. [[1, 2], [3, 5], [4, 8], [6, 7], [8, 10], [12, 16]]
Correct answer: B. [[1, 2], [3, 10], [12, 16]]
Three phases: copy intervals ending before the new start, absorb every interval starting at or before the new end, copy the rest. [4,8] absorbs [3,5], [6,7], [8,10] (8 ≤ 8 touches) → [3,10]. O(n).
More Coding Interview Problems questions
- Problem: n ≤ 10⁵ trains arrive and depart at given minutes. Find the minimum number of platforms. Which approach is O(n log n) and correct?
- Problem: Assign cookies of sizes s to children with greed factors g (a child is content if cookie ≥ greed). Maximise content children…
- Problem: A staircase has n steps; you climb 1 or 2 steps at a time. Count the distinct ways to reach the top. cpp long long ways(int n) {…
- Problem: A thief robs houses in a row but cannot rob two adjacent houses. Find the maximum loot. python def rob(a): take = skip = 0 for x…
- Problem: Same robbery, but the houses form a circle (first and last are adjacent). python def line(a): take = skip = 0 for x in a: take…
- Problem: Find the fewest coins that make an amount (−1 if impossible). python def coins(cs, amt): INF = float('inf'); dp = [0] + [INF] amt…