Permutation in String
Check if a text hides a rearrangement of a pattern
DSA, Medium, Sliding Window
Which structure or algorithm, and what does it cost.
You get two lowercase strings, pattern and text. A rearrangement of pattern uses the same letters with the same counts, in any order. Return true if some substring of text is a rearrangement of pattern. Otherwise return false.
Examples
Constraints
- 1 <= length of
pattern<= 100,000. - 1 <= length of
text<= 100,000. - Both strings hold only the letters a to z.
Your answer must contain
- The simple method and why it is too slow; the better method; code; time and memory cost; a hand trace of example 1.
Target Aim for O(n) time and O(1) memory, with n the length of text.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
A rearrangement has the same letter counts as the pattern. Which substrings of the text are long enough to match?
Hint 2 the approach
Only windows with the same length as the pattern matter. Slide one window across the text and keep its letter counts.
Hint 3 the key step
Each step adds one letter and removes one. Track how many of the 26 letters have the right count, so you never compare all 26.
Walkthrough
Full walkthrough brute force to best
Brute force
For each start position, take the next m letters of the text, count them, and compare with the counts of the pattern. With n letters in the text and m in the pattern, that is O(n * m) time. The worst case is a pattern about half as long as the text: with 100,000 letters in the text, that is around 2.5 billion steps.
Better method
Slide one window of m letters across the text. Keep the 26 letter counts of the window up to date by adding the new letter and removing the old one, and compare them with the 26 counts of the pattern at each step. This is O(26 * n) time and O(1) memory. It is correct, with a constant factor of 26.
Best method
Keep the pattern counts need and the window counts have, each as 26 numbers. Also keep matched, the number of letters whose two counts are equal. Moving the window one step changes only two letters, so update matched for those two and nothing else. A change of a count either makes it equal to the need, which adds one to matched, or moves it away from the need, which subtracts one. When matched reaches 26, every letter agrees, so the window is a rearrangement. The window always holds the m latest letters, because the old letter leaves as soon as the window is full. This makes each step O(1) work and the whole scan linear.
Hand trace
Run on pattern "abc" and text "xxcabyy". The need is one a, one b, one c, and 23 letters match at the start because their needs are 0. Letter x: window "x", matched 22 because x no longer matches. Second x: still 22. Letter c: window "xxc", c now matches, matched 23. Letter a: add a, then drop the first x, matched 24. Letter b: add b, then drop the second x. Now x is back to 0, so matched is 26. The window "cab" matches, so the answer is true.
Code
def has_rearrangement(pattern, text):
m = len(pattern)
if m > len(text):
return False
need = [0] * 26
have = [0] * 26
for ch in pattern:
need[ord(ch) - 97] += 1
matched = sum(1 for c in range(26) if need[c] == 0)
def change(c, step):
was = have[c] == need[c]
have[c] += step
return int(have[c] == need[c]) - int(was)
for i, ch in enumerate(text):
matched += change(ord(ch) - 97, 1)
if i >= m:
matched += change(ord(text[i - m]) - 97, -1)
if matched == 26:
return True
return FalseTime and memory
O(n) time, because each letter of the text is added once and removed once, with O(1) work each. O(1) memory, because there are two lists of 26 counts.
Common mistakes
- Comparing the set of letters and not their counts. With "aab" a window "abx" has a and b but is not a rearrangement.
- Forgetting to remove the letter that leaves the window. The counts then describe the whole text so far, not the last m letters.
- Building every arrangement of the pattern and searching for each one. A pattern of 10 letters already has millions of arrangements.