~/problems / Sliding window

Permutation in String

medium ~25 min

Write has_scrambled_copy(word: str, text: str) -> bool that returns True if some contiguous piece of text is a rearrangement of word: it has exactly the same letters, each the same number of times, in any order.

has_scrambled_copy("tap", "the apt pat")      # True  ("apt", and "pat" too)
has_scrambled_copy("tap", "tea party")        # False (the letters are there, but never side by side)
has_scrambled_copy("aab", "abbab")            # False (pieces "abb", "bba", "bab": never two a's)
has_scrambled_copy("aab", "bbaba")            # True  ("aba")
has_scrambled_copy("abc", "ab")               # False (text is shorter than word)
  • 1 <= len(word), len(text) <= 2 * 10^5; both contain only lowercase letters a-z and spaces.
  • A piece must be exactly len(word) characters long and taken without gaps.
  • Checking each piece from scratch costs O(len(word)) per position, too slow when both strings are long. Aim for O(len(word) + len(text)).
Show hint

two neighbouring pieces differ by one character leaving on the left and one arriving on the right. Keep letter counts for the current piece and update them in O(1) per step, along with a running tally of how many letters currently have the right count.

Topic: Sliding window. Grow right, shrink left while invalid; monotonic deque for window max/min.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc