KatInterview

438. Find All Anagrams in a 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 find all starting indices of substrings in a given string s that are anagrams of another string p. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. This means an anagram must have the same characters with the same frequencies. The core of the problem is to efficiently check for this anagram property for all substrings of s with the same length as p.

Solution

Find All Anagrams in a String in Python

from typing import List

class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        s_len, p_len = len(s), len(p)

        # Edge case: if s is shorter than p, no anagram is possible.
        if s_len < p_len:
            return []

        result = []
        # Frequency maps for p and the current window in s.
        # Using list of size 26 for lowercase English letters.
        p_counts = [0] * 26
        s_counts = [0] * 26

        # Calculate frequency map for p and the first window in s.
        for i in range(p_len):
            p_counts[ord(p[i]) - ord('a')] += 1
            s_counts[ord(s[i]) - ord('a')] += 1

        # Check if the first window is an anagram.
        if p_counts == s_counts:
            result.append(0)

        # Slide the window across the rest of s.
        for i in range(p_len, s_len):
            # Add the new character entering the window from the right.
            s_counts[ord(s[i]) - ord('a')] += 1
            # Remove the character leaving the window from the left.
            s_counts[ord(s[i - p_len]) - ord('a')] -= 1

            # Check if the current window is an anagram.
            if p_counts == s_counts:
                result.append(i - p_len + 1)

        return result

Find All Anagrams in a String in Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        int sLen = s.length();
        int pLen = p.length();

        // Edge case: if s is shorter than p, no anagram is possible.
        if (sLen < pLen) {
            return new ArrayList<>();
        }

        List<Integer> result = new ArrayList<>();
        // Frequency maps for p and the current window in s.
        // Using array of size 26 for lowercase English letters.
        int[] pCounts = new int[26];
        int[] sCounts = new int[26];

        // Calculate frequency map for p and the first window in s.
        for (int i = 0; i < pLen; i++) {
            pCounts[p.charAt(i) - 'a']++;
            sCounts[s.charAt(i) - 'a']++;
        }

        // Check if the first window is an anagram.
        if (Arrays.equals(pCounts, sCounts)) {
            result.add(0);
        }

        // Slide the window across the rest of s.
        for (int i = pLen; i < sLen; i++) {
            // Add the new character entering the window from the right.
            sCounts[s.charAt(i) - 'a']++;
            // Remove the character leaving the window from the left.
            sCounts[s.charAt(i - pLen) - 'a']--;

            // Check if the current window is an anagram.
            if (Arrays.equals(pCounts, sCounts)) {
                result.add(i - pLen + 1);
            }
        }

        return result;
    }
}

Find All Anagrams in a String in C++

class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        int s_len = s.length();
        int p_len = p.length();

        // Edge case: if s is shorter than p, no anagram is possible.
        if (s_len < p_len) {
            return {};
        }

        vector<int> result;
        // Frequency maps for p and the current window in s.
        // Using vector of size 26 for lowercase English letters.
        vector<int> p_counts(26, 0);
        vector<int> s_counts(26, 0);

        // Calculate frequency map for p and the first window in s.
        for (int i = 0; i < p_len; ++i) {
            p_counts[p[i] - 'a']++;
            s_counts[s[i] - 'a']++;
        }

        // Check if the first window is an anagram.
        if (p_counts == s_counts) {
            result.push_back(0);
        }

        // Slide the window across the rest of s.
        for (int i = p_len; i < s_len; ++i) {
            // Add the new character entering the window from the right.
            s_counts[s[i] - 'a']++;
            // Remove the character leaving the window from the left.
            s_counts[s[i - p_len] - 'a']--;

            // Check if the current window is an anagram.
            if (p_counts == s_counts) {
                result.push_back(i - p_len + 1);
            }
        }

        return result;
    }
};

Find All Anagrams in a String in TypeScript

function findAnagrams(s: string, p: string): number[] {
    const sLen = s.length;
    const pLen = p.length;

    // Edge case: if s is shorter than p, no anagram is possible.
    if (sLen < pLen) {
        return [];
    }

    const result: number[] = [];
    const pCounts = new Array(26).fill(0);
    const sCounts = new Array(26).fill(0);
    const a_charCode = 'a'.charCodeAt(0);

    // Calculate frequency map for p and the first window in s.
    for (let i = 0; i < pLen; i++) {
        pCounts[p.charCodeAt(i) - a_charCode]++;
        sCounts[s.charCodeAt(i) - a_charCode]++;
    }

    // Use a 'matches' count to track how many character counts are correct.
    // An anagram is found when matches === 26.
    let matches = 0;
    for (let i = 0; i < 26; i++) {
        if (pCounts[i] === sCounts[i]) {
            matches++;
        }
    }

    // Check if the first window is an anagram.
    if (matches === 26) {
        result.push(0);
    }

    // Slide the window across the rest of s.
    for (let i = pLen; i < sLen; i++) {
        const rightCharIndex = s.charCodeAt(i) - a_charCode;
        const leftCharIndex = s.charCodeAt(i - pLen) - a_charCode;

        // Update for the new character entering the window.
        // If its count was correct, it's now incorrect.
        if (sCounts[rightCharIndex] === pCounts[rightCharIndex]) {
            matches--;
        } else if (sCounts[rightCharIndex] === pCounts[rightCharIndex] - 1) {
            // If its count was one less, it's now correct.
            matches++;
        }
        sCounts[rightCharIndex]++;

        // Update for the old character leaving the window.
        // If its count was correct, it's now incorrect.
        if (sCounts[leftCharIndex] === pCounts[leftCharIndex]) {
            matches--;
        } else if (sCounts[leftCharIndex] === pCounts[leftCharIndex] + 1) {
            // If its count was one more, it's now correct.
            matches++;
        }
        sCounts[leftCharIndex]--;

        // If all 26 character counts match, we found an anagram.
        if (matches === 26) {
            result.push(i - pLen + 1);
        }
    }

    return result;
}

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.