Learning Outcome
Use a moving window when subarrays or substrings must remain valid under a local constraint.
Pattern Recognition
| Item | Detail |
|---|---|
| Core signal | The problem asks for longest, shortest, or count of contiguous ranges with a condition. |
| Use when | The answer is contiguous and you can restore validity by moving the left boundary. |
| Avoid when | The required invariant is not monotonic or the input constraints point to a simpler direct scan. |
Intuition
The right pointer explores new data; the left pointer removes old data until the window becomes valid again.
Exact Practice Question Names
- Longest Substring Without Repeating Characters
- Fruit Into Baskets
- Minimum Window Substring
- Permutation in String
- K-divisible Elements Subarrays
Interview Approach
- Expand right and update frequency state.
- While invalid, remove left and move left forward.
- Update best answer only when the window is valid.
- Use last-seen index optimization for no-repeat strings.
Pseudocode
left = 0
state = empty map
for right in range(n):
add a[right] to state
while window is invalid:
remove a[left] from state
left += 1
update answer from right - left + 1
Sample Dry Run
For 'abcabcbb', the window grows to 'abc'. Seeing the next 'a' moves left after the old 'a', preserving a duplicate-free window.
Edge Cases
- Empty string
- All same characters
- Constraint k = 0
- Zero-count keys left in the map
Common Mistakes
- Updating answer before shrinking invalid windows
- Using sliding window when negative numbers break monotonicity
- Forgetting to delete zero-frequency keys
Complexity
| Item | Detail |
|---|---|
| Expected time | O(n) because each pointer moves at most n times. |
| Expected space | O(k) for the tracked alphabet or distinct values. |
Java, C++ and Python Notes
- Java: prefer explicit classes and clear helper methods over clever one-liners.
- C++: use vector, unordered_map, set, priority_queue, and long long when sums can grow.
- Python: keep state readable with dict, set, deque, heapq, and lru_cache where appropriate.
Quick Revision Checklist
- Name the pattern before coding.
- State the invariant or DP state in one sentence.
- Dry-run the smallest non-trivial example.
- Close with time and space complexity.