Bitpath

Problem-Solving Patterns

A handful of patterns turn most O(n²) array and string problems into one pass. Learn to recognise them: two pointers, sliding windows, prefix sums with a map, the monotonic stack and greedy choices, each finished off with a classic problem.

  • Intermediate
  • 4 units, 12 lessons, 145 exercises
  • Python, JavaScript or TypeScript
  • Builds on Algorithm Foundations, Searching & Sorting, stacks from Data Structures

Unit 01 · 3 lessons

Two pointers

Replace a loop inside a loop with two indexes that each cross the list once

  1. > start01From both ends
  2. 02Reader and writer
  3. BOSSThe biggest tank
Unit prize
  1. 01
    From both ends

    Find a pair with a given sum in a sorted list

  2. 02
    Reader and writer

    Clean up a list in place with a slow index and a fast one

  3. BOSS
    The biggest tank

    Container with most water: move the shorter wall

Read the unit guide

Checking every pair of items costs O(n²). Two pointers is the habit of walking two indexes through the list under a rule, so that every step throws away possibilities you never need to look at again. Each index crosses the list once: O(n) time, O(1) extra memory.

Opposite ends: on a sorted list, put lo at the start and hi at the end. If their sum is too small, the smallest number is useless (even its biggest partner was not enough), so move lo up. If the sum is too big, the largest number is useless, so move hi down. Sorted order is what makes each discard safe.

Reader and writer: both indexes move left to right. The reader looks at every item; the writer marks the slot where the next keeper goes. Keepers are copied forward, nothing is deleted or shifted, and the function returns how many slots are filled. The writer can never overtake the reader, so nothing unread is ever overwritten.

The same thinking solves problems that are not about sums. For the most water between two walls, start with the widest pair and always move the shorter wall: keeping it can only give a narrower tank that is no taller.

Classic pitfalls: looping while lo <= hi when you need two different items (use lo < hi); using opposite ends on unsorted data; and forgetting what your index means. "Next free slot" and "last filled slot" differ by one, and so will your answer.

Unit 02 · 3 lessons

Sliding window

Answer questions about runs of neighbours in one pass

  1. 01Fixed windows
  2. 02Grow and shrink
  3. BOSSNo repeats
Unit prize
  1. 01
    Fixed windows

    Slide a window of k items: one in, one out

  2. 02
    Grow and shrink

    Let the window stretch on the right and tighten on the left

  3. BOSS
    No repeats

    Longest substring without repeating characters

Read the unit guide

A window is a run of neighbouring items between a left edge and a right edge. Instead of recomputing something for every possible run, you keep one window and update it as the edges move. Every item enters once and leaves at most once, so the whole scan is O(n).

Fixed size: for a window of k items, each step adds the item that enters on the right, nums[r], and subtracts the one that leaves on the left, nums[r - k]. A list of n items has n - k + 1 such windows.

Variable size: the right edge grows by one item per step and the left edge shrinks under a rule. For the shortest valid window, shrink while the window is still valid and measure inside that loop. For the longest valid window, shrink while it is invalid and measure after.

The while loop inside the for loop looks quadratic and is not. The left edge only moves forward and can never pass the right edge, so across the whole run it moves at most n times.

For "no repeated characters", keep a map from each character to the index where it was last seen. When a repeat arrives, jump the left edge to just past the old copy, but only if that copy is inside the window (prev >= lo). Skip that check and the left edge can jump backwards: the famous abba bug.

Pitfalls: a window's length is r - left + 1. Sum-based shrinking relies on every number being positive; with negative numbers, dropping an item can make the sum bigger, and you need the prefix sums of the next unit. And only reversible summaries (a sum, a count) can be updated by "removing" an item. A maximum cannot.

Unit 03 · 3 lessons

Prefix sums and hashing

Turn questions about runs of items into subtraction and one map lookup

  1. 01Running totals
  2. 02Subarray sum equals K
  3. BOSSProduct except self
Unit prize
  1. 01
    Running totals

    Any range sum in O(1) after one pass

  2. 02
    Subarray sum equals K

    Count runs with a given sum using prefix totals in a map

  3. BOSS
    Product except self

    A pass from the left, a pass from the right, no division

Read the unit guide

A prefix-sum array stores running totals: prefix[i] is the sum of the first i items. It has n + 1 entries and starts with prefix[0] = 0, the sum of nothing. The sum of the items from index i up to (not including) j is then prefix[j] - prefix[i]: one pass to build, O(1) for every range after that.

The leading zero is a convention, and it is worth it: ranges that start at index 0 need no special case. Whatever convention you use, write down what prefix[i] means. Without the zero, each entry includes its own item, and the same subtraction is off by one.

Subarray sum equals k: walk the list with a running total. A run ending here sums to k exactly when some earlier running total equals total - k. Keep a map from each running total to how many times it has occurred, starting with 0 seen once, and add that count at every step. Look up before you store, or a total can match itself.

Unlike a sliding window, this works with negative numbers, because it never assumes that a longer run has a bigger sum. Small changes answer other questions: store the first index of each total to find the longest run, or store totals modulo k to count runs divisible by k.

The idea is not tied to addition. For "product of all the other numbers", one left-to-right pass stores the product of everything before each position, and a right-to-left pass multiplies in everything after it. The starting value becomes 1, the product of nothing.

Costs: building is O(n) time and O(n) memory for the array or the map. You are trading memory for the ability to answer each question in constant time.

Unit 04 · 3 lessons

Stacks and greedy choices

Answer "next bigger" questions with a stack, and trust a greedy rule only when you can say why it is safe

  1. 01Next greater element
  2. 02Intervals: merge and schedule
  3. BOSSJump game
Unit prize
  1. 01
    Next greater element

    A stack of waiting indexes answers every position in one pass

  2. 02
    Intervals: merge and schedule

    Sort first, then one greedy pass

  3. BOSS
    Jump game

    One number, the furthest reach, decides everything

Read the unit guide

A monotonic stack answers "what is the next larger item?" for every position in one pass. The stack holds the indexes that are still waiting for an answer. When a new value arrives, it is the answer for every waiting index with a smaller value: pop them and record it. Then the new index waits too.

Because smaller values are popped before each push, the values on the stack never get larger from bottom to top. Each index is pushed once and popped at most once, so the scan is O(n) even though it has a loop inside a loop. Whatever is left at the end has no larger item after it.

Small changes give the variants. Store i - j instead of the value to get distances ("days until warmer"). Flip the comparison for "next smaller". Read the top of the stack before pushing to get the nearest larger item to the left.

A greedy algorithm makes the choice that looks best right now and never takes it back. Sorting usually comes first. To merge overlapping spans, sort by start: each span can then only overlap the block you built last. To fit the most meetings in one room, sort by end and take every meeting that starts once the room is free.

Greedy is only correct when you can argue that the local choice never hurts. Ending earliest leaves the most room for everything else. In the jump game, a larger reach can do everything a smaller one can. With coins 1, 3 and 4, taking the largest coin first pays 6 as 4 + 1 + 1, but 3 + 3 is better: a big coin can block a better mix.

When no such argument exists, greedy is a guess. Test it on small cases before trusting it, and reach for dynamic programming when it fails.

Learn Problem-Solving Patterns on your phone.

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy