Permutation in String

Check whether a string contains some rearrangement of another string's letters as one unbroken piece.

Given two strings s1 and s2 of lowercase letters, return true if some rearrangement of the letters of s1 appears in s2 as a run of consecutive characters, and false otherwise. A rearrangement of a string is also called a permutation of it, and a run of consecutive characters is called a substring.

Example 1
Input: s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains "ba", a rearrangement of "ab".
Example 2
Input: s1 = "ab", s2 = "eidboaoo"
Output: false
Explanation: s2 has a b and an a, but an o sits between them.
Solution

The Idea

Think of a word game where you hold the letter tiles a and b, and you want to know whether a line of text holds those two letters side by side somewhere, in any order. In "eidbaooo" it does: the letters b and a stand side by side at positions 3 and 4, and "ba" uses exactly your two tiles.

In "eidboaoo" the same two letters are there, but an o stands between them. The tiles have to be used together, in one unbroken piece, so the answer is false.

How do we check this without writing out every rearrangement of s1? For two letters there are only two, "ab" and "ba". But a 10-letter s1 with all letters different has 3,628,800 of them, far too many to try one by one.

We do not need the rearrangements at all. Two strings are rearrangements of each other exactly when they contain the same letters, each the same number of times. "ba" has one a and one b, just like "ab". So the question becomes: does some piece of s2 have the same letter counts as s1?

That piece must also be exactly as long as s1, here 2 letters. So we look at s2 two letters at a time: positions 0 and 1, then 1 and 2, and so on. Look at the picture below.

A window of two letters slides along s2 = eidbaooo. Windows 1 to 3, ei, id and db, do not hold one a and one b. Window 4, ba, does, so the answer is true.

The row labelled window 1 covers "ei", which has neither an a nor a b. Window 2 covers "id", also no. Window 3 covers "db": it has the b, but a d instead of the a. Window 4 covers "ba", one a and one b, so the answer is true.

Each row is the one above it, moved one place to the right. A stretch of fixed length that moves along a string like this is called a sliding window. Each move adds one letter on the right and drops one on the left, and the letters in between stay the same.

Solution Approach

Turning that idea into code means settling three things: how to compare a window with s1, how to update that comparison when the window moves, and how to tell quickly that every letter matches.

Comparing a window with s1

What should we store for each window? Only lowercase letters can appear, so an array of 26 counters, one per letter, describes any string's letters. Position 0 counts the a's, position 1 the b's, and so on, and c - 'a' turns a letter c into its position.

One array can hold both strings at once. Call it diff: each letter of s1 adds 1 to its counter, and each letter in the window subtracts 1. The window is a rearrangement of s1 exactly when all 26 counters are 0.

Moving the window

Why not count each window from scratch? That costs as many steps as s1 has letters, for every window. With a long s1 and a long s2 that adds up quickly.

The picture showed that a move changes only two letters. So a move costs two updates: the letter entering on the right subtracts 1 from its counter, and the letter leaving on the left adds 1 back.

Knowing when every letter matches

Checking all 26 counters after every move would work, and it is a fine simple version. It can be done in one check, though. Keep a number zeros: how many of the 26 counters are 0 right now.

A move changes two counters, and each change can only make a counter become 0, stop being 0, or neither. So zeros goes up or down by at most one per change, and the window matches when zeros is 26.

In the first example, window 1 ("ei") leaves the counters for a and b at 1 and those for e and i at -1, so zeros is 22. In window 3 ("db") only the counters for a and d are not 0, so it is 24, and window 4 reaches 26.

Java Solution

The method checkInclusion works in these steps:

  1. First, store the length of s1 in n. If s2 is shorter than n, no window fits, so return false.
  2. Create the array diff of 26 counters. A loop over the first n positions adds 1 for each letter of s1 and subtracts 1 for each letter of s2, so diff describes the first window.
  3. Count the counters that are 0 into zeros. If zeros is already 26, the first window matches and the method returns true.
  4. Slide the window with a second loop, where i is the position of the letter entering on the right, from n to the end of s2. The letter leaving on the left is at i - n.
  5. Each move calls the helper change twice, once per letter. It updates that letter's counter and returns +1 if the counter just became 0, -1 if it stopped being 0, and 0 otherwise. Both results are added to zeros.
  6. After each move, return true if zeros is 26. If the loop ends without a match, return false.

The main method runs both examples, a match in the very last window, two cases with a repeated letter, and an s1 longer than s2.

Java
public class PermutationInString {

    public static boolean checkInclusion(String s1, String s2) {
        int n = s1.length();
        if (n > s2.length()) {
            return false;                     // no window of s2 is long enough
        }
        int[] diff = new int[26];             // count in s1 minus count in the window
        for (int i = 0; i < n; i++) {
            diff[s1.charAt(i) - 'a']++;
            diff[s2.charAt(i) - 'a']--;
        }
        int zeros = 0;                        // letters whose counts match
        for (int d : diff) {
            if (d == 0) {
                zeros++;
            }
        }
        if (zeros == 26) {
            return true;                      // the first window already matches
        }
        for (int i = n; i < s2.length(); i++) {
            zeros += change(diff, s2.charAt(i) - 'a', -1);      // letter enters the window
            zeros += change(diff, s2.charAt(i - n) - 'a', +1);  // letter leaves the window
            if (zeros == 26) {
                return true;                  // the window is a permutation of s1
            }
        }
        return false;
    }

    // Add delta to diff[c]; return how the number of zero entries changed (-1, 0 or +1)
    private static int change(int[] diff, int c, int delta) {
        int before = diff[c] == 0 ? 1 : 0;
        diff[c] += delta;
        int after = diff[c] == 0 ? 1 : 0;
        return after - before;
    }

    public static void main(String[] args) {
        System.out.println(checkInclusion("ab", "eidbaooo"));
        System.out.println(checkInclusion("ab", "eidboaoo"));
        System.out.println(checkInclusion("ab", "xxba"));
        System.out.println(checkInclusion("aab", "abab"));
        System.out.println(checkInclusion("aab", "abba"));
        System.out.println(checkInclusion("abc", "ab"));
    }
}

Running it prints:

Output
true
false
true
true
false
false

The first true is window 4 from the picture, "ba", and the false below it is "eidboaoo", where the o keeps b and a apart.

The third line, true, comes from "ab" in "xxba", where the only match is the last window. That is why the test sits after each move. With the test at the top of the loop, before the move, the last window is never checked, and a run of that version on "xxba" returned false.

The fourth and fifth lines show that repeated letters are counted. "aab" needs two a's and one b: "abab" has "aba" at positions 0 to 2, so it prints true. "abba" has no three-letter piece with two a's, so it prints false. The last false is s1 = "abc" against the shorter "ab".

The original implementation, PermutationInString.java, is on GitHub.

Complexity

The work is one pass over s1 to fill the counters, plus one move of the window for each remaining letter of s2.

  • Time: O(n + m), with n the length of s1 and m the length of s2. The first loop runs n times, the window makes at most m - n moves with two constant-time change calls each, and counting the zeros once takes 26 steps.
  • Space: O(1), because diff always holds 26 counters, one per lowercase letter, plus the single number zeros, however long the strings are.

To list every place where a rearrangement starts, instead of stopping at the first, see Find All Anagrams in a String.