Algo-Sim › Sliding Window

Permutation in String

Medium · Sliding Window · step through it in Java, Python and C++ on your own input

Return true if some substring of s2 is a permutation (rearrangement) of s1.

Problem

Given two strings s1 and s2, return true if s2 contains a contiguous substring that is a rearrangement of all the letters of s1, and false otherwise.

Constraints

Edge cases to test

Follow-up questions

How do you compare windows in O(1)?
Keep a count of how many of the 26 letters currently match; each slide changes two counts, so it updates in O(1).
What if you need every starting index?
The same sliding window recording each match is Find All Anagrams (LC 438): O(n).

Solution

Java

public boolean checkInclusion(String s1, String s2) {
    int[] need = new int[26], window = new int[26];
    for (char c : s1.toCharArray()) need[c - 'a']++;
    int left = 0;
    for (int right = 0; right < s2.length(); right++) {
        int c = s2.charAt(right) - 'a';
        window[c]++;
        while (window[c] > need[c]) {
            window[s2.charAt(left) - 'a']--;
            left++;
        }
        if (right - left + 1 == s1.length()) {
            return true;
        }
    }
    return false;
}

Python

def check_inclusion(s1, s2):
    need, window = [0] * 26, [0] * 26
    for ch in s1: need[ord(ch) - 97] += 1
    left = 0
    for right in range(len(s2)):
        c = ord(s2[right]) - 97
        window[c] += 1
        while window[c] > need[c]:
            window[ord(s2[left]) - 97] -= 1
            left += 1
        if right - left + 1 == len(s1):
            return True
    return False

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool checkInclusion(string &s1, string &s2) {
        vector<int> need = vector<int>(26), window = vector<int>(26);
        for (char c : s1)
            need[c - 'a']++;
        int left = 0;
        for (int right = 0; right < int(s2.size()); right++) {
            int c = s2[right] - 'a';
            window[c]++;
            while (window[c] > need[c]) {
                window[s2[left] - 'a']--;
                left++;
            }
            if (right - left + 1 == int(s1.size())) {
                return true;
            }
        }
        return false;
    }
};

More Sliding Window problems