Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Interval itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)An interval is a start/end pair plus an endpoint rule. For closed intervals, touching endpoints overlap; sort valid pairs by start and maintain the farthest covered end, or insert linearly when existing ranges are already sorted and disjoint.
3 practice exercises59 interview problems
Recognize it when The output normalizes overlapping ranges rather than counting individual events.
Checking your account…
An interval is a start/end pair plus a boundary convention. Overlap cannot be decided until the contract says whether endpoints are closed, open, or half-open. Both Labs assume valid pairs with start no greater than end. Here normalization means merging coverage; it does not repair reversed endpoints.
Closed [start, end] intervals include both endpoints, so [1, 3] and [3, 5] touch and overlap at
3. Half-open [start, end) intervals make adjacent ranges non-overlapping. Write the comparison from
that rule instead of memorizing < versus <=.
Sort by start, then keep one merged frontier. If the next start is no greater than the frontier end, extend the end; otherwise the frontier is final. Sorting dominates at O(n log n), and copying output avoids mutating caller-owned interval lists.
def normalize_closed_intervals(intervals):
merged = []
for start, end in sorted((start, end) for start, end in intervals):
if not merged or start > merged[-1][1]:
merged.append([start, end])
else:
merged[-1][1] = max(merged[-1][1], end)
return mergedImplement normalize_closed_intervals(intervals). Sort copies and merge overlap or touching boundaries without mutating input. Every pair has start <= end.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def normalize_closed_intervals(intervals):
merged = []
for start, end in sorted((start, end) for start, end in intervals):
if not merged or start > merged[-1][1]:
merged.append([start, end])
else:
merged[-1][1] = max(merged[-1][1], end)
return mergedRun the existing merge Lab with unsorted closed intervals. A shared endpoint joins [1, 3] and [3, 5]; a later overlapping interval extends their frontier before a gap starts a separate point interval.
print(normalize_closed_intervals([[4, 6], [1, 3], [3, 5], [10, 10]])) followed by print(normalize_closed_intervals([]))
| Step | Executed statement | State | Why |
|---|---|---|---|
| 1 | for start, end in sorted((start, end) for start, end in intervals): |
ordered pairs = (1, 3), (3, 5), (4, 6), (10, 10) |
Start order lets one active frontier summarize processed coverage. |
| 2 | merged.append([start, end]) |
merged = [[1, 3]] |
The first pair creates a newly owned output frontier. |
| 3 | merged[-1][1] = max(merged[-1][1], end) |
start = 3; end = 5; merged = [[1, 5]] |
Equality at the boundary overlaps for closed intervals. |
| 4 | merged[-1][1] = max(merged[-1][1], end) |
start = 4; end = 6; merged = [[1, 6]] |
The overlapping pair extends the covered maximum endpoint. |
| 5 | if not merged or start > merged[-1][1]: merged.append([start, end]) |
start = 10; prior end = 6; merged = [[1, 6], [10, 10]] |
The gap finalizes the prior frontier; a point interval remains valid. |
| 6 | return merged |
result = [[1, 6], [10, 10]] |
Every input range is covered once without mutating its pair. |
| Output | |
|---|---|
| 1 | [[1, 6], [10, 10]] |
| 2 | [] |
Sorted start order makes the frontier proof possible: once the next start exceeds the covered end, all later starts do too. The max update prevents a nested shorter range from shrinking coverage, and each returned pair owns its mutable list.
When existing intervals are already sorted and disjoint, copy intervals strictly before the new range, merge every touching range, then append the untouched suffix. This is O(n) without re-sorting.
def insert_closed(intervals, new_interval):
result = []
index = 0
start, end = new_interval
while index < len(intervals) and intervals[index][1] < start:
result.append(intervals[index].copy())
index += 1
while index < len(intervals) and intervals[index][0] <= end:
start = min(start, intervals[index][0])
end = max(end, intervals[index][1])
index += 1
result.append([start, end])
result.extend(interval.copy() for interval in intervals[index:])
return resultImplement insert_closed(intervals, new_interval). Existing closed intervals are sorted and disjoint; return the merged insertion in O(n). Every existing pair and new_interval has start <= end.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def insert_closed(intervals, new_interval):
result = []
index = 0
start, end = new_interval
while index < len(intervals) and intervals[index][1] < start:
result.append(intervals[index].copy())
index += 1
while index < len(intervals) and intervals[index][0] <= end:
start = min(start, intervals[index][0])
end = max(end, intervals[index][1])
index += 1
result.append([start, end])
result.extend(interval.copy() for interval in intervals[index:])
return resultUse interval merging when ranges themselves are the output. Use start/end events for maximum overlap, room counts, or time-varying state; event tie order must reflect closed versus half-open semantics. Use a difference array when the coordinate domain is small and dense.
State endpoint semantics first, then define what the merged frontier covers. Explain why sorted start order proves no finalized interval can overlap a later one.
Normalize Closed Intervals(opens in a new tab) practices the frontier; Merge Intervals(opens in a new tab) requires recognizing that normalization pattern.
Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Interval itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Sort and merge n intervals | O(n * log(n + 1)) | O(n * log(n + 1)) | Valid fixed-size pairs with bounded comparison cost; includes sorted tuples and newly owned output lists. |
| Insert into sorted disjoint intervals | O(n) | O(n) | Copies each untouched pair and scans each affected pair at most once; no re-sorting is performed. |
O(n) for sort and merge n intervals; O(n) for insert into sorted disjoint intervals.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
Closed intervals share their endpoint, so equality is overlap rather than a gap.
Prevent it: Derive <= from the closed boundary contract.
overlaps = start < frontier[1]overlaps = start <= frontier[1]Where you will hit this: Normalize Closed Intervals(opens in a new tab)
Replacing the end directly loses coverage already established by a larger interval.
Prevent it: Keep the maximum covered endpoint during a merge.
frontier[1] = endfrontier[1] = max(frontier[1], end)Where you will hit this: Normalize Closed Intervals(opens in a new tab)
Updating an output pair also mutates the caller's pair when they are the same list.
Prevent it: Copy untouched input pairs before placing them in mutable results.
result = [original[0]]
result[0][1] = 5result = [original[0].copy()]
result[0][1] = 5Where you will hit this: Merge Intervals(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27