567. Permutation in String – Solution [Brute-Force to Best]

Here’s the question link on LeetCode 567. Permutation in String:-

https://leetcode.com/problems/permutation-in-string/description

Brute Force: Generate and Check Every Substring

The first idea is to check every substring of s2 having the same length as s1.

For every substring:

  1. Sort it.
  2. Sort s1.
  3. Compare both strings.

If they are equal, we found a permutation.

class Solution {
public:
    bool checkInclusion(string s1, string s2) {
        int m = s1.size();
        int n = s2.size();

        if(m > n)
            return false;

        sort(s1.begin(), s1.end());

        for(int i = 0; i <= n - m; i++) {
            string temp = s2.substr(i, m);

            sort(temp.begin(), temp.end());

            if(temp == s1)
                return true;
        }

        return false;
    }
};
567. Permutation in String solution

Optimal: Sliding Window + Frequency Array

Instead of sorting every substring, let’s just count how many times each character appears.

Since the problem contains only lowercase English letters, we can use an array of size 26.

For example:

s1 = "ab"

a → 1
b → 1

Now, any permutation of "ab" must have exactly these same frequencies.

So we maintain a fixed-size sliding window of length s1.size() in s2.

How does the window work?

Consider:

s1 = "ab"
s2 = "eidbaooo"

Our window size is 2.

ei → id → db → ba → ao → oo

We check the character frequencies of each window.

When moving the window:

  • Add the new character entering from the right.
  • Remove the character leaving from the left.
  • Compare the frequency arrays.

If both arrays match, we found a permutation!

class Solution {
public:
    bool checkInclusion(string s1, string s2) {
        int m = s1.size();
        int n = s2.size();

        if(m > n)
            return false;

        vector<int> freq1(26, 0);
        vector<int> freq2(26, 0);

        // Count frequencies of s1 and first window
        for(int i = 0; i < m; i++) {
            freq1[s1[i] - 'a']++;
            freq2[s2[i] - 'a']++;
        }

        if(freq1 == freq2)
            return true;

        // Slide the window
        for(int i = m; i < n; i++) {
            freq2[s2[i] - 'a']++;

            freq2[s2[i - m] - 'a']--;

            if(freq1 == freq2)
                return true;
        }

        return false;
    }
};
567. Permutation in String Optimal Solution

Leave a Reply