Rows: stretches, sorted lists and most-recent-first
After this: Match a stretch to a window, a sorted list to binary search, brackets to a stack and repeats to a hash set.
On this page · 7 sections · 3 checks
In the first lesson, one word, "sorted", changed the tool for a pair. This lesson works four more rows of the cue table. All four are about a row of values: a list of numbers or a string of characters. For each row you get the problem, the cue, the tool and a tiny example worked by hand.
A stretch in a row: the sliding window
The cue is "3 days in a row": a stretch of neighbouring items. Adding up every stretch from scratch repeats work, because two neighbouring stretches share most of their items. A keeps the total of one stretch and moves it one place at a time:
- The first window is 2 + 1 + 5 = 8.
- Slide: 2 leaves and 1 enters, so 8 − 2 + 1 = 7.
- 1 leaves and 3 enters: 7 − 1 + 3 = 9.
- 5 leaves and 2 enters: 9 − 5 + 2 = 6.
The largest total is 9. Each slide costs two operations however wide the window is, so the whole pass is O(n). Other words for the same cue are "substring" and "subarray", which mean a stretch of neighbouring characters or items. When the stretch must grow and shrink, the window does too: see A window that grows and shrinks.
- Window of 3The width is 3. Watch the sum change as the window slides: one value leaves on the left, one enters on the right.
- 02
- 11
- 25
- 31
- 43
- 52
Run an operation to begin.
One value in a sorted list: binary search
The cue is "find" plus "sorted". Lesson 1 also had a sorted list, but it asked for a pair. This asks for one value, and the tool is : look at the middle of the part that could still hold 23, and throw away the half that cannot.
lo= 0,hi= 9, middle index 4 holds 16. 16 < 23, so 23 is to the right:lo= 5.- Middle index 7 holds 56. 56 > 23, so
hi= 6. - Middle index 5 holds 23. Found at index 5, after 3 probes.
For 40, which is missing, the probes are 16, 56, 23 and 38. Then lo passes hi and the answer is −1, after 4 probes. The cost is O(log n), which means one more probe each time the list doubles: about 20 probes for a million items.
- Binary search for 23Find 23. Each probe looks at the middle of what is left and throws away the half that cannot hold 23.
- Binary search for 40
- 02
- 15
- 28
- 312
- 416
- 523
- 638
- 756
- 872
- 991
Run an operation to begin.
Most recent first: a stack
The cue is "matching brackets": the bracket that must close next is always the one opened most recently. A gives back the most recent item first. Push each opener; at each closer, pop and compare.
"([])": push(, push[.]pops[, a match.)pops(, a match. The stack is empty: balanced."([)]": push(, push[.)pops[, the wrong kind: not balanced."((": two openers are still waiting at the end: not balanced."": nothing to match: balanced.
Other cues for a stack are "undo" and "go back". The cost is O(n) time, and the stack can grow to n items.
Seen before: a hash set
The cue is "appears a second time", or "seen before", "repeated", "unique". A remembers every value read so far. On [4, 9, 2, 9, 4]: 4, 9 and 2 are new and go into the set. The next 9 is already there, so the answer is 9. The 4 also repeats, but its second copy comes later, at index 4. The cost is O(n) time and O(n) extra memory for the set.
The stack and the set in code
Java does not run on this site: the Run button runs the Python, and with Java selected the Java is shown for reading. The window and binary search have their own visualizers above; here are the other two rows, written as their tutorials write them.
In is_balancedisBalanced, an opener goes on the stack. A closer pops the top and compares it with its partner from pairs; a missing or wrong partner returns Falsefalse at once. At the end, the string is balanced only if nothing is left on the stack. In first_repeatfirstRepeat, each value is checked against the set first and added after, so the first value found in the set is the first repeat.
| Cue | Tool | Time | Extra memory |
|---|---|---|---|
| "k in a row", "stretch", "substring" | sliding window | O(n) | O(1) for a sum |
| "find" in a sorted list | binary search | O(log n) | O(1) |
| "matching brackets", "most recent first" | stack | O(n) | O(n) |
| "seen before", "repeated" | hash set | O(n) | O(n) |
Check yourself
A problem says: “Given the price of a share on each day, find the longest stretch of days in a row on which the price kept rising.” Which tool do its words point to?
A problem says: “A web page is a list of opening tags such as <b> and closing tags such as </b>. Check that every tag is closed, and that the tag closed is always the one opened most recently.” Which tool fits?
The seen-set function from this lesson, on a new row. What does it print?
def first_repeat(items): seen = set() for item in items: if item in seen: return item seen.add(item) return None
print(first_repeat([6, 1, 8, 1, 6]))import java.util.*;
public class Main { static Integer firstRepeat(int[] items) { Set<Integer> seen = new HashSet<>(); for (int item : items) { if (seen.contains(item)) { return item; } seen.add(item); } return null; }
public static void main(String[] args) { System.out.println(firstRepeat(new int[] {6, 1, 8, 1, 6})); }}Honesty notes
- Match “k in a row”, “stretch”, “substring” or “subarray” to a sliding window, and update its total by taking away what leaves and adding what enters, so the whole pass is O(n).
- Match “find” in a sorted list to binary search, and say that it costs O(log n): about 20 probes for a million items.
- Match matching brackets and “most recent first” to a stack, and “seen before” or “repeated” to a hash set: each costs O(n) time and can keep up to n items.
- Say that a sorted list points to two pointers for a pair and to binary search for one value.