Two indexes walk in from both ends until the pair adds up.
O(n) time · O(1) spaceThe patterns behind 60% of array-based interview questions.
2 algorithms5 variants2 races8 problems
2 algorithms. Each one builds on the last.
Two indexes walk in from both ends until the pair adds up.
O(n) time · O(1) spaceA window slides along the array, adding on the right and dropping on the left.
O(n) time · O(1) spaceVisualizeSame input, side by side. Watch who wins.
Why a hash map turns Two Sum into one pass, and what sorting first buys you.
Watch the raceWhy remembering the lowest price so far turns every pair into one pass.
Watch the raceThese pages answer questions about an array without checking every pair or every stretch of values. Interviewers lean on them because the brute force answer is usually O(n²) and the expected one is O(n), and the same moves suit real code that streams through logs or prices once.
Each page keeps two positions in the array and moves them by a rule that throws away work you can prove is useless. Moving a pair sum pointer drops one value with every pair it could still form; moving a window's left edge drops values already counted, so the running total updates in O(1). Two pages listed with the windows search over the answer instead.
Look at what the two positions mark. Two separate values to pair up: pointers from opposite ends, on sorted input. The edges of one stretch: a window, fixed when the size is given, variable when a condition sets it. A number you can test but not slide: binary search on the answer. The usual mistake is a variable window over negative values, where shrinking no longer lowers the sum.