Sliding window · Medium
Permutation in String: the idea to remember.
Decide whether a lowercase English string contains a contiguous permutation of a shorter string.
The core insight
Slide a fixed length window and compare its 26 character counts to the target.
Why it works
Only windows of exactly the target length can be permutations; equal frequency arrays are necessary and sufficient.
The mistake to avoid
Remove the outgoing character when the window exceeds the target length.
Time: O(26n + m), hence O(n + m)Space: O(1)
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
boolean checkInclusion(String target, String text) {
if (target.length() > text.length()) return false;
int[] need = new int[26], window = new int[26];
for (char c : target.toCharArray()) need[c - 'a']++;
for (int r = 0; r < text.length(); r++) {
window[text.charAt(r) - 'a']++;
if (r >= target.length()) window[text.charAt(r - target.length()) - 'a']--;
if (r + 1 >= target.length() && Arrays.equals(need, window)) return true;
}
return target.isEmpty();
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.