Techniques

Recursion MemoizationtechniquesMemoization caches the result of each unique recursive call so repeated subproblems aren't recomputed. Sliding WindowtechniquesThe sliding-window technique maintains a contiguous range over a sequence, expanding and shrinking it as you… Two PointertechniquesThe two-pointer technique walks two indices through a sequence — usually one at each end, or both moving…

Patterns that turn quadratic solutions into linear ones: two pointers, sliding windows, and memoized recursion.

These techniques are reusable patterns rather than specific algorithms. Each removes repeated work from a brute-force solution: pointers and windows avoid re-scanning elements, and memoization avoids recomputing subproblems.



‹ Algorithms

1. Overview

Recognising the Pattern Problembrute force too slowSorted pair / ends?Two PointerContiguous range?Sliding WindowOverlapping subproblems?MemoizationResultO(n) or polynomialTwo pointer and sliding window reduce O(n^2) scans to O(n); memoization turns exponential recursion polynomial.

Two pointer keeps two indices, typically one at each end of a sorted array moving inward, or a fast and a slow pointer moving forward. Each step moves one pointer, so the total work is linear. Sliding window is a special case where both pointers bound a contiguous subarray or substring; you extend the right edge and shrink the left edge while maintaining a running sum, count or set. Memoization caches the result of each distinct recursive call; it is top-down dynamic programming and applies whenever the same subproblem is reached by many paths.

2. When to Use Which

TechniqueTypical problemsTimeExtra space
Two PointerPair sum in sorted array, remove duplicates, palindrome check, cycle detectionO(n)O(1)
Sliding WindowLongest substring without repeats, max sum of k elements, minimum windowO(n)O(k) or O(alphabet)
Recursion MemoizationFibonacci, coin change, edit distance, grid pathsO(states x work per state)O(states)

If the input is unsorted and you need pairs, consider sorting first (O(n log n)) or a hash map. If memoized recursion hits Python's recursion limit, convert it to a bottom-up table. Related: Searching and Sorting.