Medium dsa sliding-window

Find All Anagrams in a String

The 30 second answer

An anagram of p is any substring of s that uses the same letters with the same counts. I slide a window of length p over s, keep a count array of 26 letters, and whenever the window counts match p's counts I record the start index. Adding the new right character and removing the left one updates the window in constant time.

Could you say this in an interview?

Problem Given a string s and a pattern p, return the starting indices of every anagram of p that occurs in s, in any order. Original: LeetCode 438: Find All Anagrams in a String.

Understanding the prompt The window size is fixed at p's length. Letter order inside the window does not matter, only the frequencies. If s is shorter than p, the answer is empty.

Pattern recognition A fixed-size sliding window plus frequency counting, the same idea as Valid Anagram applied to every alignment.

Brute force For every start index, sort the substring of length p and compare it with a sorted p: O(n ยท k log k).

Optimal Count the letters of p and of the first window of s. If the two int[26] arrays are equal, index 0 is a start. Then for each later right index, increment s[right], decrement s[right โˆ’ p.length()], and compare again. Arrays.equals is enough; you can also keep a 'matches' counter of how many letters currently have the right frequency if you want to avoid comparing 26 slots every step.

Alternatives Permutation in String is the same window, returning a boolean instead of the start indices. A HashMap of characters works for alphabets larger than 26 letters.

Java solution

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

public class FindAllAnagramsInAString {
    static List<Integer> findAnagrams(String s, String p) {
        var ans = new ArrayList<Integer>();
        if (s.length() < p.length()) return ans;
        var need = new int[26];
        var window = new int[26];
        for (int i = 0; i < p.length(); i++) {
            need[p.charAt(i) - 'a']++;
            window[s.charAt(i) - 'a']++;
        }
        if (Arrays.equals(need, window)) ans.add(0);
        for (int r = p.length(); r < s.length(); r++) {
            window[s.charAt(r) - 'a']++;
            window[s.charAt(r - p.length()) - 'a']--;
            if (Arrays.equals(need, window)) ans.add(r - p.length() + 1);
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(findAnagrams("cbaebabacd", "abc")); // [0, 6]
        System.out.println(findAnagrams("abab", "ab"));        // [0, 1, 2]
        System.out.println(findAnagrams("aa", "bb"));          // []
    }
}

Complexity O(|s|) time, O(1) extra space besides the output, because the count arrays have a fixed size of 26.

Edge cases

  • s shorter than p returns [].
  • Overlapping hits, as in s = "abab" and p = "ab", whose starts are 0, 1 and 2.
  • No anagram at all, as in ("aa", "bb").

Follow-ups

  • Permutation in String: stop at the first hit.
  • Unicode or mixed case: switch to a map of code points and confirm the alphabet with the interviewer.

Tests s = "cbaebabacd", p = "abc" returns [0,6]. s = "abab", p = "ab" returns [0,1,2]. s = "aa", p = "bb" returns [].

How to say it in the interview "I slide a window of length p across s and keep letter counts for the window and for p. Each step I add one character and drop one, and when the two count arrays match I record the start. Linear in s, constant extra space."

Sources (2)
  1. LeetCode 438: Find All Anagrams in a Stringleetcode.com
  2. Java SE 17 API: Arrays.equalsdocs.oracle.com