Strings are arrays too
After this: Check a palindrome from both ends, and find anagrams with a counting window.
On this page · 6 sections · 4 checks
So far every lesson has used arrays of numbers. A string is also a row of cells: each cell holds one character, and the indexes start at 0. In the string "cat", index 0 holds c, index 1 holds a and index 2 holds t. So everything you have learned works on strings too. This lesson uses two of the methods: pointers from both ends, and a window of fixed width.
From both ends: palindromes
A is a word that reads the same forwards and backwards, such as "noon" or "racecar". To check a word, compare its first letter with its last, then its second letter with its second-to-last, and go on towards the middle.
Here is "noon".
leftis on the first n andrightis on the last n. They match, so both pointers move inward.leftis on the first o andrightis on the second o. They match, so both pointers move inward.lefthas now passedright, so every pair has been compared and matched. It is a palindrome.
If two letters differ, the answer is no, and we can stop at once.
"racecar" has seven letters and takes three comparisons: r with r, a with a, and c with c. The pointers then meet on the middle e, which has no partner, so it is never compared. "racecat" takes one comparison, because r and t differ.
def is_palindrome(s): left, right = 0, len(s) - 1 while left < right: if s[left] != s[right]: return False left += 1 right -= 1 return True
print(is_palindrome("racecar"), is_palindrome("racecat"))True False
public class Main { static boolean isPalindrome(String s) { int left = 0, right = s.length() - 1; while (left < right) { if (s.charAt(left) != s.charAt(right)) return false; left++; right--; } return true; }
public static void main(String[] args) { System.out.println(isPalindrome("racecar") + " " + isPalindrome("racecat")); }}true false
A word of n letters needs at most n / 2 comparisons, because each comparison uses up two letters.
Watch it happen
The visualizer holds numbers, so the letters are shown as their positions in the alphabet: r = 18, a = 1, c = 3, e = 5. After the first check, the task changes the last letter to t (20) and runs the check again.
- Palindrome checkThe letters r a c e c a r are shown as 18 1 3 5 3 1 18. Compare the two ends and move inward.
- Write 20 at index 6
- Palindrome check
- 018
- 11
- 23
- 35
- 43
- 51
- 618
Run an operation to begin.
A window with a count map
Two words are if they use the same letters the same number of times, in any order. For example, "cba" is an anagram of "abc".
Here is a harder question: where in "cbadabc" does an anagram of "abc" start?
Order does not matter in an anagram, so what we compare is counts. A window of width 3 moves along the string, and a map holds how many times each character is in the window. This is the counting map from hash maps in practice. The word we are matching, "abc", has the counts a: 1, b: 1, c: 1.
- The first window is cba. Its counts are c: 1, b: 1, a: 1. They match, so an anagram starts at index 0.
- Slide: c leaves and d enters. The window is bad, with counts b: 1, a: 1, d: 1. No match.
- Slide: b leaves and a enters. The window is ada, with counts a: 2, d: 1. No match.
- Slide: a leaves and b enters. The window is dab, with counts d: 1, a: 1, b: 1. No match.
- Slide: d leaves and c enters. The window is abc, with counts a: 1, b: 1, c: 1. They match, so an anagram starts at index 4.
The answer is [0, 4].
Each slide is the same as in the fixed window: the character entering gets +1, and the character leaving gets −1. There is one extra rule. When a count drops to 0, we remove that character from the map. A Python Counter ignores zero counts when it compares, so this only keeps the map small.Otherwise the window's map would hold an extra entry such as d: 0, and equals would say the two maps differ.
from collections import Counter
def anagram_starts(s, p): k = len(p) need = Counter(p) # what a window must contain have = Counter(s[:k]) # counts inside the first window starts = [0] if have == need else [] for hi in range(k, len(s)): have[s[hi]] += 1 # the character entering out = s[hi - k] # the character leaving have[out] -= 1 if have[out] == 0: del have[out] # drop zero counts: this keeps the map small if have == need: starts.append(hi - k + 1) return starts
print(anagram_starts("cbadabc", "abc"))[0, 4]
import java.util.*;
public class Main { static List<Integer> anagramStarts(String s, String p) { int k = p.length(); Map<Character, Integer> need = new HashMap<>(); // what a window must contain for (char c : p.toCharArray()) need.merge(c, 1, Integer::sum); Map<Character, Integer> have = new HashMap<>(); // counts inside the first window for (int i = 0; i < k; i++) have.merge(s.charAt(i), 1, Integer::sum); List<Integer> starts = new ArrayList<>(); if (have.equals(need)) starts.add(0); for (int hi = k; hi < s.length(); hi++) { have.merge(s.charAt(hi), 1, Integer::sum); // the character entering char out = s.charAt(hi - k); // the character leaving if (have.merge(out, -1, Integer::sum) == 0) have.remove(out); // drop zero counts so the maps compare equal if (have.equals(need)) starts.add(hi - k + 1); } return starts; }
public static void main(String[] args) { System.out.println(anagramStarts("cbadabc", "abc")); }}[0, 4]
Here is how to read it.
needholds the counts of the word we are matching, andhaveholds the counts of the current window.- Counter(p) builds a map of counts from a string.need.merge(c, 1, Integer::sum) adds 1 to the count of c, and creates the entry if it is not there yet.
- The loop moves
hialong the string. s[hi - k]s.charAt(hi - k) is the character that leaves, as in the fixed window. - When the two maps are equal, the window is an anagram, and it starts at index
hi - k + 1.
Each slide changes two counts. Comparing two maps takes one step for each different character, so its cost depends on how many different characters there are, not on the length of the string.
What a slice costs
There is a shorter way to check a palindrome: reverse the string and compare. It gives the right answer, but it does more work.
s = "racecar"print(s == s[::-1]) # right answer, but s[::-1] builds a second string of n charactersTrue
String s = "racecar";System.out.println(s.contentEquals(new StringBuilder(s).reverse())); // right answer, but reverse() builds a second stringtrue
This always builds a second string of n characters, even when the first letters already differ. The two-pointer check builds nothing and stops at the first mismatch.
The same is true of taking a piece of a string. In Python, this is called a slice, and in Java a substring. Both languages copy the characters into a new string. Strings in both languages are , which means that a string cannot be changed after it is created.
- A piece from index i up to index j copies j − i characters.
- Reading one character, with s[i]s.charAt(i), is O(1), which means that it takes the same few steps however long the string is.
So keep indexes, and read one character at a time. A loop that takes a slice at every step can quietly turn an O(n) pass into O(n²) work.
Check yourself
What does this print?
def is_palindrome(s): left, right = 0, len(s) - 1 while left < right: if s[left] != s[right]: return False left += 1 right -= 1 return True
print(is_palindrome("racecar"), is_palindrome("racecat"))public class Main { static boolean isPalindrome(String s) { int left = 0, right = s.length() - 1; while (left < right) { if (s.charAt(left) != s.charAt(right)) return false; left++; right--; } return true; }
public static void main(String[] args) { System.out.println(isPalindrome("racecar") + " " + isPalindrome("racecat")); }}How many comparisons does the check make for racecar (7 letters), and for racecat?
What does anagram_starts("cbadabc", "abc")anagramStarts("cbadabc", "abc") return?
A loop reads s[i:j]s.substring(i, j) at every step. What does each slicesubstring cost?
Connect
- Check a palindrome from both ends in at most n / 2 comparisons, without building a reversed copy.
- Find every anagram of a word in a string with a window of fixed width and a map of counts.
- Say that a slice or substring copies its characters in Python and Java, and read one character at a time by index instead.