How to use the Sliding Window Visualizer
- 1. Choose a problemMaximum sum of k numbers, shortest subarray reaching a target, longest substring without repeats, or the maximum of every window.
- 2. Enter your inputNumbers separated by commas or a string, plus k or the target.
- 3. ReplayThe window is highlighted in blue with L and R marked; the best window turns green at the end.
Worked example: fixed window
For 2, 1, 5, 1, 3, 2, 9, 4 with k = 3, the first window sums to 8. Each slide adds the new number and drops the one leaving, instead of re-adding all three: 7, 9, 6, 14 and finally 15. The best window is 2, 9, 4 at indexes 5–7, with sum 15. That's 6 window sums computed with about one addition and one subtraction each, so O(n) instead of O(n·k).
Worked example: variable window
For the string "abcabcbb", the window grows to "abc". When the next "a" arrives, L jumps past the earlier "a", and so on. The longest window without repeats is "abc", length 3, found in one pass of 8 steps. The window maximum mode uses a deque of indexes whose values fall from front to back, so each window's maximum is always at the front.
When to reach for a sliding window
- The problem asks about a contiguous subarray or substring.
- You can update the answer cheaply when one element enters and one leaves.
- For a variable window, the rule must be monotonic: growing can only break it, shrinking can only fix it. That's why the shortest-subarray mode needs non-negative numbers.
- If the window rule depends on counts of items, keep those counts in a hash map and update them as items enter and leave.
Frequently asked questions
What's the difference from two pointers?
A sliding window is a two-pointer method where both pointers move the same way and you track what's between them.
Why are negative numbers refused in one mode?
With negatives, shrinking the window can raise the sum, so the shrink rule stops being safe. Prefix sums with a hash map handle that case.
How long can the input be?
30 numbers or 40 characters.
Is the sliding window visualizer free?
Yes. Everything in the sliding window visualizer works without signing up. The first time you ask for a result, we ask once for your name and WhatsApp number; after that the sliding window visualizer and every other Uncodemy tool open straight away.