Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern
Problem: Merge overlapping booking intervals.
Problem: Merge overlapping booking intervals.
def merge(iv):
iv.sort(); out = []
for s, e in iv:
if out and s <= out[-1][1]:
out[-1][1] = max(out[-1][1], e)
else:
out.append([s, e])
return out
print(merge([[8, 10], [1, 3], [2, 6], [15, 18], [6, 7], [17, 20]]))What is printed?- A. [[1, 7], [8, 10], [15, 20]]
- B. [[1, 6], [6, 7], [8, 10], [15, 20]]
- C. [[1, 7], [8, 10], [15, 18], [17, 20]]
- D. [[1, 3], [2, 7], [8, 10], [15, 20]]
Correct answer: A. [[1, 7], [8, 10], [15, 20]]
Sort by start, then extend the last interval while the next one starts at or before its end. [1,3]+[2,6]+[6,7] touch at 6 → [1,7]; [15,18]+[17,20] → [15,20]. Using max(end, e) matters when an interval is nested. O(n log n).
More Coding Interview Problems questions
- Problem: Remove the fewest meetings so that the rest do not overlap (meetings that only touch at an endpoint are fine). python def…
- Problem: Find the minimum number of meeting rooms needed for a list of meetings [start, end). python import heapq def rooms(iv)…
- Problem: A car starts with an empty tank at one of n petrol pumps on a circular route; pump i gives gas[i] and the trip to the next costs…
- Problem: Each child must get at least one sweet, and a child with a higher rating than a neighbour must get more than that neighbour. Find…
- Problem: Each position holds the maximum jump length from it. Return the minimum jumps to reach the last index. python def jumps(a): j =…
- Problem: Can you reach the last index if a[i] is the maximum jump from i? java static boolean canReach(int[] a) { int far = 0; for (int i…