Skip to main content
← CONCEPTS / ALGORITHMS & DATA STRUCTURES
An end-to-end domain learning journey

Core Algorithm Patterns: Two Pointers, Fast
& Slow, Sliding Window & DP.

Four foundational algorithmic paradigms—Two Pointers, Fast & Slow Pointers, Sliding Window, and Dynamic Programming—that turn brute-force O(n^2) or O(2^n) searches into optimal O(n) or polynomial-time solutions.
Start the journey7 sections· Last modified Nov 29, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When durability and read throughput pull in opposite directions, Fast & Slow, Sliding, identify the structural invariant first: monotonic sorted/array bounds call for Two Pointers or Sliding Window, cyclic state transitions call for Fast & Slow, and overlapping subproblems with optimal substructure call for Dynamic Programming.

TL;DR30-second simplified summary
▾

Core Mechanics: Most brute-force sequence and optimization algorithms fail at scale because they re-examine identical ranges (O(n^2)) or recompute identical subproblems (O(2^n)).

Visual & Structural Flow: Depicts Sliding Window Expand / Shrink State Machine (EXPAND RIGHT -> VALID WINDOW -> SHRINK LEFT); Selecting the Optimal Linear/Polynomial Pattern (Inspect Invariant -> Monotonic Bounds -> Subproblem DAG -> O(n) / O(W)).

Trade-Offs & Production: Compare pattern alternatives when choosing between time, auxiliary memory, and recursion depth. Real-world systems frequently compose patterns: Longest Increasing Subsequence (LIS) pairs DP state (tails[len]) with binary search to drop O(n^2) to O(n log n), while.

Failure Modes & Application: Practice these concrete algorithmic and systems problems that directly apply Sliding Window monotonic deques, cycle detection, and divide-and-conquer.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
PRIME Core Invariants & Workload Constraints
Establish concrete scale, latency, memory, and concurrency bounds for Core Algorithm Patterns: Two Pointers, Fast & Slow, Sliding Window & DP before selecting data structures or storage components.
Failure Boundaries & Operational Trade-Offs
Identify hot-key skew, partial failures, resource leaks, and when simpler single-node or standard alternatives outperform complex designs.
Full walkthrough · 7 stages
01
STAGE 01 · WHAT IT ISL4 · FUNDAMENTALS

What are the Four Core Algorithm Patterns.

Why this matters: The mechanism: understand how the Four Core Algorithm Patterns works from first principles.

Most brute-force sequence and optimization algorithms fail at scale because they re-examine identical ranges (O(n^2)) or recompute identical subproblems (O(2^n)). These four patterns eliminate redundant work by exploiting structural invariants:

  • Two Pointers: On sorted or partitioned data, left and right move monotonically, pruning O(n^2) pairs to O(n) in O(1) space.
  • Fast & Slow Pointers (Floyd's): Advancing slow by +1 and fast by +2 detects cycles and midpoints in O(n) time and O(1) space.
  • Sliding Window: Expands right to include state and shrinks left only when a monotonic invariant breaks (O(n) amortized).
  • Dynamic Programming (DP): Caches overlapping subproblems (dp[i] or dp[i][j]) via memoization or bottom-up tabulation.
Window Invariant

Sliding Window Expand / Shrink State Machine

Invariant satisfiedMinimize / violatedInvariant restoredNeed more elementsEXPAND RIGHTAdd s[right] to stateVALID WINDOWUpdate best answerSHRINK LEFTEvict s[left], left++

Each pointer crosses each element at most once, bounding total work to 2n operations = O(n) amortized time.

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

Why we need Structural Invariants at Production Scale.

Why this matters: The problem: see what breaks without Structural Invariants at Production Scale under real concurrency or scale.

Think of Why we need Structural Invariants at Production Scale as the intuition layer for Core Algorithm Patterns: Two Pointers, Fast & Slow, Sliding Window & DP: The problem: see what breaks without Structural Invariants at Production Scale under real concurrency or scale.

Production bottlenecks—from API gateway rate limiters and stream deduplication to config diff engines and knapsack schedulers—rely on these patterns to keep tail latency O(n) and memory bounded.

Design Trade-Off

Why we need Structural Invariants at Production Scale

Before · Unbounded Coupling
  • No backpressure on spikes
  • Implicit shared state
  • Cascading tail latency
After · Bounded & Observable
  • Explicit capacity budgets
  • Isolated failure domains
  • Predictable p99 latency
Engineering Decision Framework
Problem
How to implement Core Algorithm Patterns: Two Pointers, Fast & Slow, Sliding Window & DP without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When durability and read throughput pull in opposite directions, fast & Slow, Sliding, identify the structural invariant first: monotonic sorted/array bounds call for Two Pointers or Sliding Window, cyclic state transitions call for Fast & Slow, and overlapping subproblems with optimal substructure call for Dynamic Programming.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Core Algorithm Patterns: Two Pointers, Fast & Slow, Sliding Window & DP experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

API Gateway Sliding-Window Rate Limiter

Scanning a full timestamp log on every request degraded to O(n) under 50k RPS bursts. A Sliding Window deque (evicting < now - 60s from left while pushing now at right) reduced per-request amortized work to O(1) (<0.3 ms p99).

Memory-Bounded Diff Engine (1D Rolling DP)

Computing Levenshtein edit distance on 20,000-line configs with a 2D dp[m][n] matrix allocated 1.6 GB RAM and OOMKilled. Compressing DP state to two 1D rolling rows (O(min(m, n)) space) cut RAM to 160 KB.

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

Where each Pattern Applies (and When to Switch).

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Think of Where each Pattern Applies (and When to Switch) as the intuition layer for Core Algorithm Patterns: Two Pointers, Fast & Slow, Sliding Window & DP: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Matching the wrong pattern—such as using a shrinkable Sliding Window on an array with negative weights—silently breaks correctness.

ChoiceWhat it buysWhat it costs
Two Pointers / Sliding WindowO(n) time, O(1)–O(k) space for sorted pair sums, partitions, and non-negative contiguous subarrays.Negative numbers break shrink monotonicity; switch to Prefix Sum + HashMap (`O(n)` space).
Fast & Slow PointersDetects cycles and finds cycle entry (`a = (k-1)L + c`) in O(1) space without a HashSet.Requires functional graph/next-pointer determinism; must guard `fast != null && fast.next != null`.
Dynamic ProgrammingSolves min/max cost and counting problems when greedy local choices fail.Can require `O(n * W)` time; avoid when greedy (Dijkstra, Huffman) is provably optimal.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

How to implement Sliding Window & 1D Compressed DP Safely.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

In 0/1 Knapsack (dp[i][w] = max(dp[i-1][w], val[i] + dp[i-1][w - wt[i]])), row i depends only on row i-1 at smaller weights.

Iterating w backward (W down to wt[i]) in a 1D array preserves dp[i-1][w - wt[i]] intact; iterating forward silently turns 0/1 Knapsack into Unbounded Knapsack.

Request & State Flow

How to implement Sliding Window & 1D Compressed DP Safely

CallerService EntryCore ProcessorState Store1. Submit bounded request2. Apply domain invariant3. Persist or read state4. Return verified response
# 1. Minimum Window Substring (Sliding Window, O(|s| + |t|))
from collections import Counter

def min_window(s: str, t: str) -> str:
 need = Counter(t)
 have, required, formed = {}, len(need), 0
 left, best = 0, (float('inf'), 0, 0)
 for right, ch in enumerate(s):
 have[ch] = have.get(ch, 0) + 1
 if ch in need and have[ch] == need[ch]:
 formed += 1
 while formed == required:
 if right - left + 1 < best[0]:
 best = (right - left + 1, left, right)
 out = s[left]
 have[out] -= 1
 if out in need and have[out] < need[out]:
 formed -= 1
 left += 1
 return '' if best[0] == float('inf') else s[best[1]:best[2] + 1]

# 2. 0/1 Knapsack with O(W) 1D rolling array (backward capacity loop)
def knapsack_01(weights: list[int], values: list[int], W: int) -> int:
 dp = [0] * (W + 1)
 for wt, val in zip(weights, values):
 for w in range(W, wt - 1, -1):
 dp[w] = max(dp[w], val + dp[w - wt])
 return dp[W]
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

Alternatives & Complexity Trade-Offs.

Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Think of Alternatives & Complexity Trade-Offs as the intuition layer for Core Algorithm Patterns: Two Pointers, Fast & Slow, Sliding Window & DP: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Compare pattern alternatives when choosing between time, auxiliary memory, and recursion depth.

Component Topology

Alternatives & Complexity Trade-Offs

CalleringressRouter / APIcomputeProcessorstorageState Layercontrolrequestdispatchread/write
ChoiceWhat it buysWhat it costs
Top-Down Memoization vs. Bottom-Up TabulationTop-down computes only reachable states and is quick to prototype.Crashes with `RecursionError` above ~10^4 depth; bottom-up enables 1D `O(W)` compression.
Sorting + Two Pointers vs. Hash Map (2-Sum)Two Pointers uses O(1) extra space and avoids hash-collision worst cases.Costs `O(n log n)` to sort and alters original indices unless paired with index tuples.
Sliding Window vs. Prefix Sum + Hash MapSliding Window runs in O(1) space for non-negative subarray sums.Fails on negative weights; Prefix Sum + HashMap handles negatives in O(n) time and O(n) space.
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

Production Pattern Selection & Composition.

Why this matters: Production architecture: see how the components compose end to end under real load.

Think of Production Pattern Selection & Composition as the intuition layer for Core Algorithm Patterns: Two Pointers, Fast & Slow, Sliding Window & DP: Production architecture: see how the components compose end to end under real load.

Real-world systems frequently compose patterns: Longest Increasing Subsequence (LIS) pairs DP state (tails[len]) with binary search to drop O(n^2) to O(n log n), while Sliding Window Maximum pairs a Sliding Window with a monotonic decreasing deque (O(n)) to track rolling p100 latency spikes without O(n log k) heap overhead.

Pattern Decision Tree

Selecting the Optimal Linear/Polynomial Pattern

Inspect InvariantSorted / Cycle / SubproblemMonotonic BoundsSubproblem DAGPage 0O(n) / Page 2Page 3

Identify whether the problem exhibits monotonicity, cyclic pointers, or overlapping subproblems before writing loops.

07
STAGE 07 · PROBLEMS SOLVED & FURTHER DEEP DIVEL7 · STAFF / PRINCIPAL

Problems solved & Related Concepts.

Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.

Think of Problems solved & Related Concepts as the intuition layer for Core Algorithm Patterns: Two Pointers, Fast & Slow, Sliding Window & DP: Applied problems: connect these internals to concrete system design and debugging scenarios.

Practice these concrete algorithmic and systems problems that directly apply Sliding Window monotonic deques, cycle detection, and divide-and-conquer.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 4
Score: 0/4

In a 1D space-compressed 0/1 Knapsack DP (`dp[w]`), what happens if you iterate `w` forward from `wt` to `W` instead of backward from `W` down to `wt`?

Recommended Learning Flow