Skip to contentKEEP THE CRAFTTHE SANCTUARY

Interval

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…

Interval Code Labs

Mental Model

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.

Endpoint Semantics Come First

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 <=.

Normalize Overlapping Closed Intervals

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.

Merge Closed Intervals

Reference
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 merged
Practice

Implement normalize_closed_intervals(intervals). Sort copies and merge overlap or touching boundaries without mutating input. Every pair has start <= end.

Public tests

  • Verify closed-boundary merging

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Merge Closed Intervals

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 merged

Trace Touching Closed Boundaries and a Finalized Frontier

Run 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.
Print 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.

Insert into an Ordered Disjoint Set

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.

Insert into Disjoint Intervals

Reference
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 result
Practice

Implement 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.

Public tests

  • Verify linear merged insertion

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Insert into Disjoint Intervals

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 result

Choose Intervals or Events

Use 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.

Interval Endpoints and Overlap Mistakes

  • Applying the wrong touching rule silently changes scheduling results.
  • Sorting by end for a merge frontier does not guarantee all overlaps become adjacent.
  • Mutating input pairs can violate ownership expectations.
  • Re-sorting an already ordered insertion problem loses the intended linear bound.

Explain It in an Interview

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 Version Note

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)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Sort and merge n intervalsO(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 intervalsO(n)O(n)Copies each untouched pair and scans each affected pair at most once; no re-sorting is performed.

Space

O(n) for sort and merge n intervals; O(n) for insert into sorted disjoint intervals.

Assumptions

  • Valid fixed-size pairs with bounded comparison cost; includes sorted tuples and newly owned output lists.
  • Copies each untouched pair and scans each affected pair at most once; no re-sorting is performed.

Invariants Worth Saying Aloud

  1. Input pairs satisfy start <= end; normalization here merges ranges rather than reversing invalid pairs.
  2. The merged frontier end is the maximum endpoint covered by the processed overlapping group.
  3. A later start beyond the frontier end proves that frontier final under sorted-start order.

When To Use Or Avoid Interval

Use It When

  • Merge closed ranges in sorted-start order when the ranges themselves are the output.
  • Use linear insertion when the existing interval order and disjointness are guaranteed.

Choose Another Tool When

  • Use sweep events for peak overlap counts rather than materialized merged ranges.
  • Do not apply the closed touching rule to half-open scheduling intervals.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Using a strict overlap test for touching closed ranges

Closed intervals share their endpoint, so equality is overlap rather than a gap.

Prevent it: Derive <= from the closed boundary contract.

Avoid

overlaps = start < frontier[1]

Use instead

overlaps = start <= frontier[1]

Shrinking the frontier with a nested shorter interval

Replacing the end directly loses coverage already established by a larger interval.

Prevent it: Keep the maximum covered endpoint during a merge.

Avoid

frontier[1] = end

Use instead

frontier[1] = max(frontier[1], end)

Aliasing an input pair into mutable output

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.

Avoid

result = [original[0]]
result[0][1] = 5

Use instead

result = [original[0].copy()]
result[0][1] = 5

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.