Explain merge intervals.
Skip to solutionKEEP THE
mediumDSA
How do you merge overlapping intervals?
586 views
01
Understand the problem
intervalssorting
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Sort intervals by start, then sweep: if the current interval overlaps the last merged one (start <= lastEnd), extend the end; otherwise append it. O(n log n) dominated by the sort.
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Sort then sweep
Run Playgrounddef merge(intervals):
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for start, end in intervals[1:]:
if start <= merged[-1][1]: # overlap
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return merged
# --- demo ---
print(merge([[1, 3], [2, 6], [8, 10], [15, 18]])) # [[1, 6], [8, 10], [15, 18]]05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 64 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.