Medium dsa sliding-window

Permutation in String

The 30 second answer

I need to know whether any permutation of s1 appears as a substring of s2. That is the same fixed window as Find All Anagrams, except I return true at the first frequency match and false if I reach the end without one.

Could you say this in an interview?

Problem Return true if one permutation of s1 is a substring of s2, otherwise false. Original: LeetCode 567: Permutation in String.

Understanding the prompt A permutation of s1 is an anagram of s1. You only need a yes or no, not the location. If s2 is shorter than s1, the answer is false.

Pattern recognition Fixed-size sliding window with frequency counts, length equal to s1.

Brute force Generate every permutation of s1 and search for it in s2, which is factorial in |s1|. Checking every substring of length |s1| by sorting is O(|s2| · |s1| log |s1|).

Optimal Build count arrays for s1 and for the first window of s2. If they match, return true. Slide one character at a time and compare after each update. Exit early on the first match.

Alternatives Reuse Find All Anagrams and test whether the list of starts is non-empty. The inlined boolean version is the one to write in an interview.

Java solution

import java.util.Arrays;

public class PermutationInString {
    static boolean checkInclusion(String s1, String s2) {
        if (s1.length() > s2.length()) return false;
        var need = new int[26];
        var window = new int[26];
        for (int i = 0; i < s1.length(); i++) {
            need[s1.charAt(i) - 'a']++;
            window[s2.charAt(i) - 'a']++;
        }
        if (Arrays.equals(need, window)) return true;
        for (int r = s1.length(); r < s2.length(); r++) {
            window[s2.charAt(r) - 'a']++;
            window[s2.charAt(r - s1.length()) - 'a']--;
            if (Arrays.equals(need, window)) return true;
        }
        return false;
    }

    public static void main(String[] args) {
        System.out.println(checkInclusion("ab", "eidbaooo")); // true
        System.out.println(checkInclusion("ab", "eidboaoo")); // false
        System.out.println(checkInclusion("ab", "a"));        // false
    }
}

Complexity O(|s2|) time, O(1) extra space for the 26-letter counts.

Edge cases

  • s2 shorter than s1, as in ("ab", "a"), returns false.
  • A match that is not a prefix, as in ("ab", "eidbaooo"), which is true because of "ba".
  • No match, as in ("ab", "eidboaoo").

Follow-ups

  • Return every start index: that is Find All Anagrams.
  • The characters are not limited to lowercase English: use a map.

Tests ("ab", "eidbaooo") returns true. ("ab", "eidboaoo") returns false. ("ab", "a") returns false.

How to say it in the interview "This is an anagram search: I slide a window the length of s1 over s2, update letter counts in constant time, and return true as soon as the counts match. Linear in s2."

Sources (1)
  1. LeetCode 567: Permutation in Stringleetcode.com