Binary search: how it works and when to use it
Binary search
Binary search halves a sorted range at every step, so a million items take about 20 checks. Signals, a worked 2D grid example, code and practice.
With a 1 min 56 s video
A sliding window keeps a run of neighbors and moves it along the input, so each item is handled once. Signals, a worked example, code and practice.
The video
LeetCode 3Open the video page
This is LeetCode problem three.
Given a string, find the length of the longest substring with no repeated characters.
Take the string pwwkew.
A substring is a run of letters that sit next to each other.
The run wke has no repeats, so the answer is three.
One way is to check every substring for repeats.
That work grows like n squared or worse, which is slow for long strings.
A faster idea is a sliding window.
We keep a left edge and a right edge.
The right edge moves forward one letter at a time.
When a letter repeats, the left edge jumps past its earlier copy.
To jump quickly, we keep a map.
It stores the last position where we saw each letter.
Positions count from zero.
At position zero, p is new.
At one, w is new, so the length is two.
At two, w repeats.
It was last seen at one, so left moves to two.
Then k and e are new, so the best length becomes three.
At five, w repeats.
It was last seen at two, so left moves to three.
Here is the JavaScript.
We create the map, with left and best at zero.
Right moves across the string.
If the letter was seen inside the window, left jumps past it.
We save its position and update best.
Then we return best.
The map can hold old positions left of the window.
In abba, the last a was seen at zero, but left is at two.
The check against left ignores it, so left never moves backward.
Each letter is visited once, so the time grows in step with the string length.
The map holds one entry per distinct letter, so extra memory depends on the alphabet.
Map lookups take constant time on average.
A sliding window with a map of last positions finds the longest substring without repeats in one pass.
A sliding window is a run of neighbors in a list or a string. You move it from left to right. Each step, one new item comes in on the right. When the run breaks a rule, items leave on the left. You keep a small summary of what is inside, like a sum or a count of letters, and update it as items come and go. You never recount the whole run. That turns "check every run" into a single pass.
Many problems ask about runs of neighbors. "The longest stretch with no repeated letter." "The biggest total of 3 numbers in a row." "The shortest stretch that adds up to at least 7."
The slow way checks every possible run. A list of 8 items has 36 runs: 8 runs of one item, 7 runs of two, and so on, down to 1 run of all eight. The count grows with the square of the length. A list of 10,000 items has about 50 million runs.
The window avoids that. Two markers, left and right, show where the run starts and ends.
right moves one step every time, so every item comes in once.left only moves forward, so every item leaves at most once.So each item is handled at most twice, however long the input is.
There are two kinds of window:
k items wide. Each step, one item comes in and one goes out.Look for these signals in the problem:
A sliding window is a poor fit when the items don't need to be neighbors. That kind of problem is about a "subsequence". It also fails when adding an item can both fix and break the rule. Sums with negative numbers are the usual trap, as the mistakes section below explains.
This is the example from the video. It is LeetCode 3, Longest Substring Without Repeating Characters. In our words: find the length of the longest run of neighboring characters where no character appears twice.
Our string is abcbdeaf, with positions 0 to 7.
We keep a map from each character to the last position where we saw it. A map is a lookup table: you give it a key, like "b", and it gives back the value stored for that key in one step.
Each step, right reads one character. If we saw it before inside the window, left jumps to just past that earlier copy. Then we write down the new position and check the window's length.
| right | letter | left | window | best |
|---|---|---|---|---|
| 0 | a | 0 | a | 1 |
| 1 | b | 0 | ab | 2 |
| 2 | c | 0 | abc | 3 |
| 3 | b | 2 | cb | 3 |
| 4 | d | 2 | cbd | 3 |
| 5 | e | 2 | cbde | 4 |
| 6 | a | 2 | cbdea | 5 |
| 7 | f | 2 | cbdeaf | 6 |
Two steps matter:
right finds a second b. The map says the first b was at position 1, which is inside the window. So left jumps to 2, right after it. The window becomes cb.right finds a second a. The map says the first a was at position 0. But the window now starts at 2, so that old a is no longer inside it. We ignore it, and left stays put.The answer is 6, the run cbdeaf from position 2 to 7.
function lengthOfLongestSubstring(s) {
const last = new Map(); // character -> the last index where we saw it
let left = 0;
let best = 0;
for (let right = 0; right < s.length; right++) {
const ch = s[right];
if (last.has(ch) && last.get(ch) >= left) {
left = last.get(ch) + 1; // jump just past the earlier copy
}
last.set(ch, right);
best = Math.max(best, right - left + 1);
}
return best;
}
lengthOfLongestSubstring("abcbdeaf"); // 6
The check last.get(ch) >= left is what makes step 6 work. Without it, left could jump backward.
For "the biggest total of k numbers in a row", add the new number and subtract the one that just left.
function maxSumOfK(nums, k) {
let sum = 0;
for (let i = 0; i < k; i++) sum += nums[i]; // the first window
let best = sum;
for (let right = k; right < nums.length; right++) {
sum += nums[right] - nums[right - k]; // one in, one out
best = Math.max(best, sum);
}
return best;
}
maxSumOfK([2, 1, 5, 1, 3, 2], 3); // 9, from 5 + 1 + 3
For "the shortest run with a total of at least target", grow on the right. While the window still works, record it and shrink from the left. This version expects positive numbers.
function shortestWithSumAtLeast(nums, target) {
let left = 0;
let sum = 0;
let best = Infinity;
for (let right = 0; right < nums.length; right++) {
sum += nums[right]; // grow
while (sum >= target) { // shrink while the window still works
best = Math.min(best, right - left + 1);
sum -= nums[left];
left++;
}
}
return best === Infinity ? 0 : best;
}
shortestWithSumAtLeast([2, 3, 1, 2, 4, 3], 7); // 2, from 4 + 3
Most window problems are one of these two shapes. Only the rule and the summary change.
Programmers describe speed with Big-O notation. It says how the work grows as the input grows, and ignores fixed costs. O(n) means the work grows in step with n, the length of the input. O(n²) means it grows with the square: double the input, and the work goes up four times.
right moves n times. left also moves at most n times in total, even though there is a loop inside a loop. Each map lookup takes about one step on average.c is the number of different characters the map holds. For plain English letters, that is a small fixed number. The fixed-size and grow-and-shrink versions only keep a few numbers. Their memory is O(1), which means it stays the same however long the input is.Compare that with checking every run: O(n²) runs, and O(n³) work if you also rescan each run for repeats.
left move backward. In the example, the old a at position 0 is outside the window. If you jump to "last position + 1" without checking, left goes back to 1. The window then holds both bs, and the code answers 7 instead of 6. Use the >= left check, or write left = Math.max(left, last.get(ch) + 1).left to right, both included, has right - left + 1 items.s[i] in JavaScript reads one UTF-16 unit, a piece of how the text is stored. That is fine for the letters, digits and symbols in interview problems. Some emoji take two units, so real-world text may need Array.from(s).Try these in order. Each one is the same loop with a different rule or summary.
A sliding window keeps a run of neighbors and a small summary of what is inside. The right edge reads each item once, and the left edge only moves forward. That makes problems about runs take one pass instead of checking every run.
Type a problem, a pattern or a system to design. You get a narrated video like the one above, usually ready in 5 to 9 minutes.
3 free videos with your own AI key. An AI key is a code from an AI company, such as Anthropic or OpenAI. Your own AI account pays for the writing. See pricing
Make a video