v9.1.1
Menu

Chapter 13: Patterns & Miscellaneous

Week 13

Master essential algorithmic patterns that appear across countless interview problems: interval manipulation, monotonic stacks, sliding window optimizations, divide and conquer strategies, greedy reasoning, and line sweep techniques. These patterns are the connective tissue between data structures and problem-solving mastery.

Topics
7
Demos
4
Videos
3
Min read
36

Chapter Overview

This final chapter covers algorithmic patterns that do not fit neatly into a single data structure category but appear with remarkable frequency in interviews and real-world systems. Each pattern represents a reusable problem-solving template.

Interval problems teach you to reason about overlapping ranges---scheduling meetings, merging time slots, or detecting conflicts. Monotonic stacks unlock efficient solutions to "next greater element" problems that would otherwise require nested loops. Sliding window maximum combines deques with the sliding window pattern for O(n) range-max queries.

Divide and conquer shows how breaking a problem into independent subproblems (and combining their solutions) leads to elegant algorithms like merge sort and Karatsuba multiplication. Greedy algorithms demonstrate when making the locally optimal choice at each step provably yields the globally optimal result. Line sweep transforms 2D geometric or scheduling problems into sorted event processing.

Mastering these patterns is about recognizing which template applies to a new problem. Once you identify the pattern, the implementation follows naturally from the template.

Chapter Roadmap

Click any topic to jump in

Explainer videoInteractive demo
1
Interval Problems

Representation, overlap detection, and linear-time insertion into sorted intervals.

Interval Representation and Overlap DetectionInsert Interval
2
Merge Intervals

$O(n \log n)$ sort-and-sweep with careful edge-case handling.

Sort-and-Merge StrategyEdge Cases in Merging
Multiple approaches

Each tackles a different aspect

3
Monotonic Stack

Amortized $O(n)$ next/previous greater/smaller via stack invariants.

Next Greater ElementMonotonic Stack Variants
4
Sliding Window Maximum

Monotonic deque gives $O(n)$ — beating heap-based $O(n \log k)$.

Deque-Based Maximum TrackingWhy Not a Heap?
Multiple approaches

Each tackles a different aspect

5
Divide and Conquer

Master Theorem template and Kadane as the linear alternative to $O(n \log n)$.

The Divide-and-Conquer TemplateMaximum Subarray (Kadane's Algorithm)
6
Greedy Algorithms

Greedy-choice property, exchange arguments, and the Jump Game reach invariant.

Greedy Choice PropertyJump Game
Builds on previous
7
Line Sweep

Event-based processing for maximum-overlap and meeting-rooms problems.

Event-Based ProcessingMeeting Rooms: Minimum Rooms Needed

Topics

7 topics in this chapter

A calendar app receives a new meeting request and must say at once whether it clashes with anything already booked. A video editor must know which clips cover the playhead, and a memory allocator must find the reserved block that contains an address. Comparing the new range with every stored range works, but the comparison itself is fiddly: two ranges can be disjoint, touch at an endpoint, partly overlap, or one can contain the other, and hand-written case lists usually miss one.

The previous chapter ended with Segment Tree, which answered aggregate queries over fixed index ranges. This final chapter turns to reusable patterns, and intervals come first because ranges appear everywhere. An interval is a pair [start, end], and nearly all interval logic reduces to one test: two intervals overlap exactly when each starts no later than the other ends. Sorting by start then lines the ranges up so that related intervals sit next to each other, and a single left-to-right pass replaces the all-pairs comparison.

We first derive the overlap test and its endpoint conventions. Then we insert a new interval into a sorted, non-overlapping list in one linear pass.

Definition

An interval [a,b][a, b] with a≤ba \le b is the set of points from a to b. Two closed intervals [a1,b1][a_1, b_1] and [a2,b2][a_2, b_2] overlap if and only if a1≤b2a_1 \le b_2 and a2≤b1a_2 \le b_1, and their intersection is then [max⁡(a1,a2),min⁡(b1,b2)][\max(a_1, a_2), \min(b_1, b_2)]. For half-open intervals the inequalities become strict. Interval problems ask how a collection of such ranges relate: which overlap, how to combine them, and where a new one fits.

In this topic

  1. 1Interval Representation and Overlap Detection
  2. 2Insert Interval
1 of 2
Interval Representation and Overlap Detection

Intervals A = [a1, b1] and B = [a2, b2] relate in six ways: either one entirely first, a partial overlap from either side, or containment. Rather than test each case, negate the easy ones. They are disjoint exactly when b1 < a2 or b2 < a1. By De Morgan's law they overlap when a1 <= b2 and a2 <= b1, one test covering all four overlapping cases. The shared part is [max(a1, a2), min(b1, b2)]. Whether touching endpoints count depends on the convention: closed [1, 5] and [5, 8] share the point 5, while half-open meeting slots do not.

Mathematical Intuition

Two intervals [a1,b1][a_1, b_1] and [a2,b2][a_2, b_2] overlap iff a1≤b2∧a2≤b1a_1 \leq b_2 \land a_2 \leq b_1 (the standard two-inequality test). Detecting overlap is O(1)O(1); detecting pairwise overlaps in a set is O(n2)O(n^2) naively but O(nlog⁡n)O(n \log n) after sorting by start (sweep-line). The convention on closed vs. half-open endpoints changes which inequalities are strict — be consistent.

Example:

Do intervals [1, 5] and [3, 8] overlap? What about [1, 5] and [6, 9]?

2 of 2
Insert Interval

Given intervals sorted by start that do not overlap, insert a new interval [l, r] and merge whatever it touches. Because the list is sorted, the existing intervals fall into three consecutive groups. Those with end < l finish before the new one begins, so they are copied unchanged. Those that overlap [l, r] are absorbed: l becomes the smallest start and r the largest end among them. The rest, with start > r, are copied after the merged interval. One pass costs O(n)O(n). Binary search finds the boundaries in O(log⁡n)O(\log n), but building the output still costs O(n)O(n).

Mathematical Intuition

Given a sorted list of non-overlapping intervals and a new interval [l,r][l, r], insert in O(n)O(n): copy intervals ending before ll, merge all intervals overlapping [l,r][l, r] by taking min⁡\min of starts and max⁡\max of ends, then copy remaining intervals. Linear time is optimal since the output may differ in up to nn positions.

Example:

Insert [4, 8] into [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]].