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.
Best Time to Buy and Sell Stock
Core idea: To sell on day
ifor the most profit, you only ever care about the cheapest price before dayi. So sweep left to right, keep a running minimum, and at every day ask "what if I sold today?" โ no need to revisit the past.
Problem, rephrased
You're tracking the daily price of a single stock, one number per day, in the order the days happened. You're allowed exactly one buy and one later sell โ you buy on some day, then sell on a strictly later day. You can also choose to do nothing.
Return the maximum profit you could have made. If no profit is possible (prices only ever fall), return 0 โ you simply don't trade.
The catch that makes it interesting: you must buy before you sell. You can't sell on day 3 and buy back the dip on day 5 to "explain" it โ time only moves forward.
Formally: given an array prices where prices[i] is the price on day i, return the largest value of prices[j] - prices[i] over all pairs with i < j, or 0 if every such difference is negative.
| Prices | Output | Why |
|---|---|---|
[7,1,5,3,6,4] |
5 | buy at 1 (day 1), sell at 6 (day 4) โ 6 - 1 |
[7,6,4,3,1] |
0 | prices only fall โ never trade |
[1,2,3,4,5] |
4 | buy at 1, sell at 5 |
[3,3,3] |
0 | flat โ best you can do is break even |
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