ARTICLE · Analysis

Which pattern when

Read the tell, name the pattern; read n, name the complexity.

Article2 tables© Arthur Bernier Jr39 rows

Two tables from the algorithms prep notes, verbatim: the problem "tell" that points at a pattern, and the input size that tells you which complexity will pass. The home page carries the first table as a live filter.

Which pattern when#

Rows marked ★ use only moves Session 9.3 already handed you: the frequency counter, two pointers, sliding window, binary search, sorting and the stack. The third column is the condition the pattern needs, or the input that breaks it; say it out loud before you pick the pattern.

Problem TELLPatternCondition or counterexample
★ sorted array + targetbinary search / two pointersthe array is already sorted; unsorted input costs an O(n log n) sort first
★ contiguous subarray / substringsliding window or prefix suma target-sum window needs every value >= 0; [3, -2, 4, 1] with target 5 breaks it, so negatives go to prefix sum
★ subarray sum equals k / count subarraysprefix sum + hash mapnone; negatives are fine, which is why it replaces the window there
top k / kth largest / kth smallestheap (size k) or quickselectquickselect is O(n) on average and O(n^2) on an unlucky pivot; the heap is O(n log k) always
k-way merge / "k sorted lists"min-heap of headseach list is already sorted
running mediantwo heapsnone
next greater / next smaller / spanmonotonic stacknone
sliding window max/minmonotonic dequethe window size k is fixed
shortest path, unweightedBFSevery edge costs the same; one weighted edge and BFS is wrong
shortest path, weighted non-negativeDijkstrano negative edge weights
shortest path, negative edgesBellman-Fordno negative cycle reachable from the source (it can detect one, not route through it)
all combinations / permutations / subsetsbacktrackingn is small; the output itself is n! or 2^n items
count ways / min cost / max value, overlapping subproblemsdynamic programmingthe same subproblem must come up again; if nothing repeats, it is plain recursion
optimal substructure + greedy-choice worksgreedy (prove exchange argument)counterexample: coins 1, 3, 4 and target 6; greedy takes 4 + 1 + 1, optimal is 3 + 3
connected components / "union" / "same group"union-find or DFSthe graph is undirected; directed groups need strongly connected components
dependencies / prerequisites / orderingtopological sortthe graph is directed with no cycle; a cycle means no valid order exists
prefix matching / autocomplete / many wordstrienone
★ intervals / meetings / overlapssort by start, then sweepnone
★ max non-overlapping intervalssort by end, greedysort by end, not start; one long early interval breaks the sort-by-start version
linked list middle / cyclefast & slow pointersnone
in-place array of 1..ncyclic sort / index as hashthe values are exactly 1..n (or 0..n-1)
duplicate in array of 1..n, O(1) spaceFloyd cycle on indicesn+1 values, each in 1..n
majority elementBoyer-Moore votinga majority (more than n/2 copies) exists; if it is not promised, verify with a second pass
★ matching brackets / nested structurestacknone
grid traversalBFS/DFS with directions arraynone
multi-source spread (rotting, distance to nearest)multi-source BFSevery source starts at the same time and every step costs the same
minimize the maximum / "min capacity such that..."binary search on the answerthe check is monotone: if capacity c works, every larger capacity works too
XOR / parity / "appears once"bit manipulationevery other value appears an even number of times
n <= 20 and subsetsbitmask enumerationn is about 20 or less; 2^n masks
LRU / LFUMap insertion order or DLL + mapnone
string equality under rotation/patternKMP / hashinghashing can collide; KMP is exact

Constraint -> acceptable complexity#

nTarget complexityTypical approach
n <= 12O(n!)permutations, brute force
n <= 25O(2^n)bitmask, subsets, backtracking
n <= 100O(n^4)nested loops, 3D DP
n <= 500O(n^3)Floyd-Warshall, interval DP
n <= 10^4O(n^2)2D DP, pairs
n <= 10^6O(n log n)sort, heap, binary search, divide & conquer
n <= 10^8O(n)single pass, hash map, two pointers, sliding window
biggerO(log n) / O(1)binary search, math, bit tricks

Rule of thumb: ~10^8 simple operations per second in JS. Put your n into the formula once and compare the result with 10^8.

Worked once, with n = 10,000 items. The nested-loop version is n^2 = 10,000 × 10,000 = 100,000,000 operations, about one second in JS. The sort-first version is n log n ≈ 10,000 × 14 = 140,000 operations, well under a millisecond. The n^2 already counts both loops (the outer runs n times, the inner runs n times inside each), so you do not multiply by n again.

See also