Permutation in String - Sliding Window Pattern
Permutation in String in Java using the Sliding Window pattern: problem statement, approach, template, complexity, and interview tips.
Permutation in String
Problem Statement
Return true if s2 contains a permutation of s1 as a substring.
Pattern: Sliding Window
Maintain a window over a contiguous range and grow or shrink it while tracking its state.
Use this pattern when the problem asks for the longest, shortest or best contiguous subarray or substring that satisfies a condition.
Approach
- Expand the right edge and add the new element to the window state.
- While the window is invalid, shrink from the left and update the state.
- Record the best answer whenever the window is valid.
Pattern Template (Java)
int left = 0;
for (int right = 0; right < n; right++) {
// add nums[right] to the window state
while (/* window is invalid */) {
// remove nums[left] from the window state
left++;
}
// update the answer using the window [left, right]
}
Adapt this template to the exact rules of Permutation in String: decide what state you track, what condition moves the loop forward, and what the final answer is.
Complexity
O(n) time because each index enters and leaves the window once; space depends on the window state.
Interview Tips
- Choose the window state first (counts, sum, set) before writing the loop.
- Fixed-size windows can skip the inner while loop.
- Start with a brute-force idea, state its complexity, then explain how the Sliding Window pattern improves it.
- Walk through a small example and at least one edge case (empty input, a single element, duplicates).
Related Problems
- Maximum Average Subarray I
- Longest Substring Without Repeating Characters
- Minimum Window Substring
- Longest Repeating Character Replacement
Continue Learning
Parent: DSA Interview Learning Path | Previous: Minimum Window Substring | Next: Longest Repeating Character Replacement
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.