Algorithmssliding window
Two Pointer Sliding Window
TT
Testlaa Team
May 14, 2026•1 min read
Sliding window is two pointers where window length changes: fix one violation at a time by moving left after extending right.
Try this in Python
def min_subarray_len(target: int, nums: list[int]) -> int:
left = 0
s = 0
best = 10**9
for right, x in enumerate(nums):
s += x
while s >= target:
best = min(best, right - left + 1)
s -= nums[left]
left += 1
return 0 if best == 10**9 else best
print(min_subarray_len(7, [2, 3, 1, 2, 4, 3]))
Key takeaways
- Prefix sum inside window is just running sum variable.
- Shrink while valid to find minimum length.
- Beware empty array and impossible case.
Tags:
Two pointersPythonStudents
