Permutation in String
Check whether a string contains some rearrangement of another string's letters as one unbroken piece.
Given two strings s1s2trues1s2false
Example 1
Output: true
Explanation: s2 contains "ba", a rearrangement of "ab".
Example 2
Output: false
Explanation: s2 has a b and an a, but an o sits between them.
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 s1s1
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 s2s1
That piece must also be exactly as long as s1s2
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
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'c
One array can hold both strings at once. Call it diffs1s1
Moving the window
Why not count each window from scratch? That costs as many steps as s1s1s2
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
A move changes two counters, and each change can only make a counter become 0, stop being 0, or neither. So zeroszeros
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
Java Solution
The method checkInclusion
- First, store the length of
ins1 . Ifn is shorter thans2 , no window fits, so returnn .false - Create the array
of 26 counters. A loop over the firstdiff positions adds 1 for each letter ofn and subtracts 1 for each letter ofs1 , sos2 describes the first window.diff - Count the counters that are 0 into
. Ifzeros is already 26, the first window matches and the method returnszeros .true - Slide the window with a second loop, where
is the position of the letter entering on the right, fromi to the end ofn . The letter leaving on the left is ats2 .i - n - Each move calls the helper
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 tochange .zeros - After each move, return
iftrue is 26. If the loop ends without a match, returnzeros .false
The mains1s2
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:
true
false
true
true
false
false
The first truefalse
The third line, truefalse
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 truefalsefalses1
The original implementation,
Complexity
The work is one pass over s1s2
- Time: O(n + m), with n the length of
and m the length ofs1 . The first loop runs n times, the window makes at most m - n moves with two constant-times2 calls each, and counting the zeros once takes 26 steps.change - Space: O(1), because
always holds 26 counters, one per lowercase letter, plus the single numberdiff , however long the strings are.zeros
To list every place where a rearrangement starts, instead of stopping at the first, see