Problems on text
After this: Check brackets with a stack and find the longest stretch with no repeated character with a window.
On this page · 4 sections · 4 checks
The last lesson worked on rows of numbers. A piece of text is a row too: a row of characters, read from left to right. This lesson works two problems on text. The first needs a stack, and the second needs a sliding window.
4. Valid parentheses
Some examples first. "{[()]}" is valid: each bracket closes the one opened most recently. "([)]" is not: the [ is still open when ) arrives. "((" is not, because nothing is closed, and ")(" is not, because it closes before it opens. The empty text "" is valid: there is nothing to close.
That empty text is an : an input at the edge of what the problem allows. Interviewers like to ask about them, so this tutorial pins one or two for every problem.
Pattern: a stack. The next closer must match the opener that came last. A stack always gives back the last thing put on it. So push every opener, and for every closer pop the top and check that the two are a pair.
- Run the programRun it and step through. Each opening bracket goes on top of the stack. Each closing bracket takes the top one off and compares the two.
def is_valid(text): pairs = {")": "(", "]": "[", "}": "{"} stack = [] for ch in text: if ch in pairs: if not stack or stack.pop() != pairs[ch]: return False else: stack.append(ch) return len(stack) == 0
print(is_valid("{[()]}"))run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The map pairs gives the opener for each closer. For each character:
- If it is a closer and the stack is empty, there is nothing to match: the answer is Falsefalse.
- If it is a closer, pop the top. If that opener is the wrong kind, the answer is Falsefalse.
- Otherwise it is an opener: push it.
At the end, the text is valid only if the stack is empty. On "{[()]}" the stack grows to three openers, then shrinks to none, and the function returns Truetrue.
Cost. O(n) time: each character is pushed or popped once. Extra memory: O(n) for the stack, because a text of only openers pushes them all.
5. Longest stretch with no repeated character
In "streets" the answer is 4, from "stre". In "abcabcbb" it is 3, in "abba" it is 2, in "aaaa" it is 1, and in "" it is 0.
Pattern: a sliding window. A is a stretch of the row between two positions. Keep a window, from left to right, that holds no repeat. Move right one character at a time. When the new character is already inside the window, move left to the place right after its earlier copy. A map remembers the last position of each character, so finding that copy is one lookup.
- Run the programRun it and step through. right moves one letter each time. Watch left: it stays at 0 until the second e, then it jumps.
def longest_unique(text): last = {} left = 0 best = 0 for right, ch in enumerate(text): if ch in last and last[ch] >= left: left = last[ch] + 1 last[ch] = right best = max(best, right - left + 1) return best
print(longest_unique("streets"))run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
Follow "streets":
s,t,r,eare all new. The window grows to"stre", andbestbecomes 4.- The second
e(position 4) was last seen at 3, inside the window.leftjumps to 3 + 1 = 4. - The second
t(position 5) was last seen at 1. That is beforeleft, so it is not in the window, andleftstays at 4. - The last
swas last seen at 0, also beforeleft. The window is"ets", length 3, andbeststays 4.
Step 3 is why the test last[ch] >= leftseenAt >= left is there. Without it, left would jump back to 2 at the second t, and the function would wrongly give 6 for "streets" and 3 for "abba". A lesson in Talking through it and testing it finds this bug on purpose.
Cost. O(n) time: right visits each character once, and left only moves forwards. Extra memory: the map, which grows with the number of different characters.
Run it
Check yourself
A text holds only the brackets ( ) [ ] { }. You must say whether each one is closed by the right kind, in the right order. Which tool fits?
The bracket checker is reading {[()]} and has read the first three characters, {[(. What does the stack hold? The left end is the bottom.
Complete the line that runs when the letter ch was last seen inside the window. It must move the left edge of the window to the position right after that last copy, so that the program prints 4.
def longest_unique(text): last = {} left = 0 best = 0 for right, ch in enumerate(text): if ch in last and last[ch] >= left: ____________________ # ← move the left edge past the repeat last[ch] = right best = max(best, right - left + 1) return best
print(longest_unique("streets"))import java.util.*;
public class Main { static int longestUnique(String text) { Map<Character, Integer> last = new HashMap<>(); int left = 0; int best = 0; for (int right = 0; right < text.length(); right++) { char ch = text.charAt(right); Integer seenAt = last.get(ch); if (seenAt != null && seenAt >= left) { ____________________ // ← move the left edge past the repeat } last.put(ch, right); best = Math.max(best, right - left + 1); } return best; }
public static void main(String[] args) { System.out.println(longestUnique("streets")); }}Every letter is the same. What does this print?
def longest_unique(text): last = {} left = 0 best = 0 for right, ch in enumerate(text): if ch in last and last[ch] >= left: left = last[ch] + 1 last[ch] = right best = max(best, right - left + 1) return best
print(longest_unique("aaaa"))import java.util.*;
public class Main { static int longestUnique(String text) { Map<Character, Integer> last = new HashMap<>(); int left = 0; int best = 0; for (int right = 0; right < text.length(); right++) { char ch = text.charAt(right); Integer seenAt = last.get(ch); if (seenAt != null && seenAt >= left) { left = seenAt + 1; } last.put(ch, right); best = Math.max(best, right - left + 1); } return best; }
public static void main(String[] args) { System.out.println(longestUnique("aaaa")); }}- Check brackets with a stack: push each opener, pop for each closer and compare, and accept only if the stack ends empty.
- Say what an edge case is, and test the bracket checker on the empty text, a closer first and openers that are never closed.
- Find the longest stretch with no repeated character with a sliding window and a map of each character's last position.
- Explain why the window moves its left edge only when the earlier copy is inside the window, and why both solutions are O(n).