KatInterview

567. Permutation in String

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to determine if any permutation of a string s1 exists as a substring within another string s2. An essential property of permutations is that they are anagrams of each other, meaning they contain the exact same characters with the exact same frequencies. For instance, "ba" is a permutation of "ab" because both have one 'a' and one 'b'. This transforms the problem into finding if any substring of s2 of length len(s1) is an anagram of s1.

Solution

Permutation in String in Python

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        n1 = len(s1)
        n2 = len(s2)

        # If s1 is longer than s2, it's impossible for s2 to contain a permutation of s1.
        if n1 > n2:
            return False

        # Use lists of size 26 to store character frequencies.
        s1_counts = [0] * 26
        s2_counts = [0] * 26

        # Populate frequency maps for s1 and the initial window in s2.
        for i in range(n1):
            s1_counts[ord(s1[i]) - ord('a')] += 1
            s2_counts[ord(s2[i]) - ord('a')] += 1

        # Compare the frequency maps for the first window.
        if s1_counts == s2_counts:
            return True

        # Slide the window across s2.
        for i in range(n1, n2):
            # Add the new character entering the window from the right.
            s2_counts[ord(s2[i]) - ord('a')] += 1
            # Remove the old character leaving the window from the left.
            s2_counts[ord(s2[i - n1]) - ord('a')] -= 1

            # Check for a match after each slide.
            if s1_counts == s2_counts:
                return True

        # If no permutation is found after checking all windows, return False.
        return False

Permutation in String in Java

import java.util.Arrays;

class Solution {
    public boolean checkInclusion(String s1, String s2) {
        int n1 = s1.length();
        int n2 = s2.length();

        // If s1 is longer than s2, it's impossible for s2 to contain a permutation of s1.
        if (n1 > n2) {
            return false;
        }

        // Use arrays of size 26 to store character frequencies.
        int[] s1Counts = new int[26];
        int[] s2Counts = new int[26];

        // Populate frequency maps for s1 and the initial window in s2.
        for (int i = 0; i < n1; i++) {
            s1Counts[s1.charAt(i) - 'a']++;
            s2Counts[s2.charAt(i) - 'a']++;
        }

        // Compare the frequency maps for the first window.
        if (Arrays.equals(s1Counts, s2Counts)) {
            return true;
        }

        // Slide the window across s2.
        for (int i = n1; i < n2; i++) {
            // Add the new character entering the window from the right.
            s2Counts[s2.charAt(i) - 'a']++;
            // Remove the old character leaving the window from the left.
            s2Counts[s2.charAt(i - n1) - 'a']--;

            // Check for a match after each slide.
            if (Arrays.equals(s1Counts, s2Counts)) {
                return true;
            }
        }

        // If no permutation is found after checking all windows, return false.
        return false;
    }
}

Permutation in String in C++

class Solution {
public:
    bool checkInclusion(string s1, string s2) {
        int n1 = s1.length();
        int n2 = s2.length();

        // If s1 is longer than s2, it's impossible for s2 to contain a permutation of s1.
        if (n1 > n2) {
            return false;
        }

        // Use vectors of size 26 to store character frequencies.
        vector<int> s1_counts(26, 0);
        vector<int> s2_counts(26, 0);

        // Populate frequency maps for s1 and the initial window in s2.
        for (int i = 0; i < n1; ++i) {
            s1_counts[s1[i] - 'a']++;
            s2_counts[s2[i] - 'a']++;
        }

        // Compare the frequency maps for the first window.
        if (s1_counts == s2_counts) {
            return true;
        }

        // Slide the window across s2.
        for (int i = n1; i < n2; ++i) {
            // Add the new character entering the window from the right.
            s2_counts[s2[i] - 'a']++;
            // Remove the old character leaving the window from the left.
            s2_counts[s2[i - n1] - 'a']--;

            // Check for a match after each slide.
            if (s1_counts == s2_counts) {
                return true;
            }
        }

        // If no permutation is found after checking all windows, return false.
        return false;
    }
};

Permutation in String in TypeScript

function checkInclusion(s1: string, s2: string): boolean {
    const n1 = s1.length;
    const n2 = s2.length;

    // If s1 is longer than s2, it's impossible for s2 to contain a permutation of s1.
    if (n1 > n2) {
        return false;
    }

    // Use arrays of size 26 to store character frequencies.
    const s1Counts = new Array(26).fill(0);
    const s2Counts = new Array(26).fill(0);
    const aCharCode = 'a'.charCodeAt(0);

    // Populate frequency maps for s1 and the initial window in s2.
    for (let i = 0; i < n1; i++) {
        s1Counts[s1.charCodeAt(i) - aCharCode]++;
        s2Counts[s2.charCodeAt(i) - aCharCode]++;
    }

    // Helper function to compare two frequency arrays.
    const areArraysEqual = (arr1: number[], arr2: number[]): boolean => {
        for (let i = 0; i < 26; i++) {
            if (arr1[i] !== arr2[i]) {
                return false;
            }
        }
        return true;
    };

    // Compare the frequency maps for the first window.
    if (areArraysEqual(s1Counts, s2Counts)) {
        return true;
    }

    // Slide the window across s2.
    for (let i = n1; i < n2; i++) {
        // Add the new character entering the window from the right.
        s2Counts[s2.charCodeAt(i) - aCharCode]++;
        // Remove the old character leaving the window from the left.
        s2Counts[s2.charCodeAt(i - n1) - aCharCode]--;

        // Check for a match after each slide.
        if (areArraysEqual(s1Counts, s2Counts)) {
            return true;
        }
    }

    // If no permutation is found after checking all windows, return false.
    return false;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.