Optimal: fixed window of counts
Time O(n) (plus 26 per step in the simple version) Space O(26)Count s1. Slide a window of length m over s2 with its own counts; whenever the 26 counts match, return true. Track the number of matching letters to compare in O(1).
s1 = "ab", s2 = "eidbaooo"Step 1/4Window "ei": counts don't match {a: 1, b: 1}.
import java.util.Arrays;
class Solution {
public boolean checkInclusion(String s1, String s2) {
int m = s1.length();
if (m > s2.length()) return false;
int[] need = new int[26], window = new int[26];
for (char c : s1.toCharArray()) need[c - 'a']++;
for (int right = 0; right < s2.length(); right++) {
window[s2.charAt(right) - 'a']++;
if (right >= m) window[s2.charAt(right - m) - 'a']--;
if (right >= m - 1 && Arrays.equals(need, window)) return true;
}
return false;
}
}Verdict: Linear scan of s2.