String and Scan
What is this?
There is no exotic algorithm here β you just walk through a string or array one time, from start to finish, while carrying along one small piece of information as you go. Maybe it is a running sum, a count, or the best value you have seen so far. The careful part is naming that one quantity precisely and knowing the exact moment to read it off; do that and the answer appears in a single pass.
π‘ Fun fact: Best Time to Buy and Sell Stock is one of the most-asked warm-up questions at big tech companies, yet the trick is almost embarrassingly simple β just remember the cheapest price seen so far. The challenge is resisting the urge to write a slow nested-loop solution.
π The 4 problems in this chapter are free. Sign in with Google or Microsoft to start solving.
Core idea: a huge class of array and string problems needs nothing more than one left-to-right pass while you carry a small running quantity β a length difference, an accumulated shift, a count, or a best-so-far. The answer falls out as you scan; there is no second loop and no extra structure.
The pattern
Each problem walks the input once and maintains a single piece of state that you update at every position. The art is naming that state precisely and knowing exactly when to read it off.
- Single-pass case analysis. When comparing two strings, split on their lengths first, then walk once and allow exactly one mismatch β the case structure does the work that brute force would do with nested loops.
- Suffix or prefix accumulation. When each position is affected by everything after (or before) it, sweep from that end and carry a running sum, so each element's final value is computed in O(1).
- Count per run. When neighbors of the same kind form runs, the answer for each run depends only on its length; tally contributions run by run as you scan.
- Track best-so-far. When you want the optimal pair under an ordering constraint, remember the best left-hand value seen so far and test each new element against it.
The common thread: one variable, one pass, updated at every step.
The problems
One Edit Distance β two strings are one edit apart only if their lengths differ by at most one. Branch on the length case, then scan once: at the first mismatch, either skip one character (insert/delete) or step both (replace) and require the rest to match.
Shifting Letters β each shift applies to a prefix, so the total shift on a position is the sum of all shifts from there onward. Sweep right to left accumulating a running suffix sum, and apply it to each character with a modulo-26 wrap.
Remove Colored Pieces if Both Neighbors are the Same Color β a run of k identical colors yields k - 2 valid moves for that player. Scan, measure each run, and tally each player's moves; compare the totals to decide the winner.
Best Time to Buy and Sell Stock β track the minimum price seen so far; at each day, the best profit is the price minus that running minimum. Keep the best profit across the single pass.
Key takeaways
- Many sequence problems need just one linear pass and one running variable.
- Name your state precisely β length case, suffix sum, run length, or best-so-far β and update it every step.
- Suffix and prefix sums turn "depends on everything after me" into O(1) per element.
- Track a min or best-so-far to solve ordered-pair optimizations without nested loops.
- The instinct to build here β sweep once, carry a little state β underpins sliding windows and prefix-sum chapters later.
One Edit Distance
Core idea: Two strings are one edit apart if you can turn one into the other with exactly one insert, delete, or replace β no more, no fewer. You do not need the full edit-distance DP table for this; a single linear scan suffices. First make
sthe shorter string so there's only one shape to reason about. If their lengths differ by more than one, the answer is immediatelyFalseβ you'd need at least two edits. Otherwise scan both strings together until the first mismatch. At that mismatch the whole question collapses into one of two checks: if the lengths are equal, the only allowed edit is a replace, so the characters after the mismatch must be identical (s[i+1:] == t[i+1:]); if the lengths differ by one, the only allowed edit is an insert/delete, so you skip the extra character in the longer string and the rest must line up (s[i:] == t[i+1:]). If you scan all the way to the end ofswith no mismatch, the strings share a common prefix β they're one edit apart only if the longer one has exactly one trailing character. That single piece of case analysis runs in O(n) time and O(1) extra space.
The problem, rephrased
You're building the autocorrect engine behind a search box. A user typed a word, and you have a dictionary word you suspect they meant. Before you offer "did you meanβ¦?", you want a cheap test: is the typed word just one keystroke away from the dictionary word β one letter swapped, one letter dropped, or one letter added? Not two changes, not zero (an exact match is not a suggestion) β exactly one.
Given two strings s and t, return True if they are exactly one edit distance apart, where a single edit is one of:
- Replace one character (lengths stay equal),
- Insert one character into
s(sotis one longer), or - Delete one character from
s(sotis one shorter β the mirror of insert).
This is LeetCode 161 β One Edit Distance.
| Input | Means | Output |
|---|---|---|
s = "abcde", t = "abXde" |
one replace (c β X) |
True |
s = "abde", t = "abcde" |
one insert (c added) |
True |
s = "cab", t = "ad" |
length diff 1 but two mismatches | False |
s = "abc", t = "abc" |
identical β zero edits, not one | False |
s = "", t = "a" |
one insert into the empty string | True |
The trap is the "exactly one" part: zero edits (s == t) is a False, and two-or-more edits is also a False. You're looking for the razor-thin middle.
Sign in to continue reading
The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.
Sign in to read the full lesson