leetcode.3
The sliding window technique is a common two-pointer pattern for array and string problems. By maintaining a window that moves across the sequence, many problems can be solved in O(n) time.
Core idea
- Use two pointers,
left and right, to represent the window boundaries.
- Move
right to expand the window.
- When the window satisfies a shrink condition, move
left to contract it.
- Update the answer while the window changes.
Template code
Classic problems
Typical use cases
- Finding the best value over a continuous subarray or substring
- String matching problems
- Fixed-length window problems
- Longest or shortest subarray satisfying a condition
Time complexity
Although there are two loops, each element is visited at most twice—once by right and once by left—so the overall time complexity is O(n). Last modified on April 17, 2026