You have the logic in your head: "Expand right, shrink left." You write the code. You run the test case.
Output: 0. Or IndexOutOfBounds. Or an infinite loop.
Sliding Window seems simple, but the shrinking logic is where 90% of bugs hide. In this guide, we will debug the most common reasons why your window "shrinks wrong" and give you a checklist to fix it.
TL;DR — Debugging Checklist
- The Loop: Use
while (invalid)to shrink, notif. - The Order: Expand -> Shrink -> Update Result.
- The Update: Only update
max/minwhen the window is valid (usually after the shrink loop). - The Trap: Negative numbers break the "shrink fixes it" logic.
Common bug scenarios
1. The "If" instead of "While" trap
You check if the window is invalid, remove one element, and continue.
- Bug: The window might still be invalid after removing one element!
- Symptom: Your window size is larger than allowed, or sums are slightly off.
- Fix: Always use
while (invalid) { shrink }.
2. Left pointer moves too early (or too late)
- Scenario: You increment
leftbefore updating the window state (e.g., removing from sum). - Symptom: The sum/count excludes an element that is still technically inside the window boundaries
[left, right].
3. Window condition mis-checked
- Scenario: You check
sum == Kinside the shrink loop instead of outside. - Symptom: You miss valid windows because you shrank past them.
Pattern: “expand while condition valid → shrink when invalid”
The most robust mental model to prevent shrinking bugs is:
- Expand (add
nums[right]). - Loop (
whilecondition is broken). - Shrink (remove
nums[left], incrementleft). - Check/Update Result (now that window is valid).
Visualizing the State:
At the end of the while loop, the window [left, right] is guaranteed to be valid (or empty). This is the safe time to update maxLength.
Debugging checklist
If your code is failing, run through this list:
- Print Window Boundaries: Inside the loop, print
left,right, and the currentsumormap.console.log(L:{right} Sum:${sum})
- Replicate with Simple Data: Don't debug with the massive failed test case. Use
[1, 1, 10, 1]or"abcba". - Check Edge Cases:
- Does it handle the first element correctly?
- Does it handle an empty array?
- Negative Numbers: Remember, if you have negatives, shrinking might not fix the condition. (See When NOT to Use).
Real code example: Incorrect vs Correct
Problem: Find the length of the smallest subarray with sum .
❌ The Buggy Version
function minSubArrayLen(target, nums) {
let left = 0, sum = 0, minLen = Infinity;
for (let right = 0; right < nums.length; right++) {
sum += nums[right];
if (sum >= target) { // BUG: Should be 'while'
minLen = Math.min(minLen, right - left + 1);
sum -= nums[left];
left++;
}
}
return minLen === Infinity ? 0 : minLen;
}Why it fails: If nums = [1, 1, 1, 1, 100] and target = 7. When we hit 100, sum is 104. We shrink once (remove 1). Sum is 103. Loop ends. We report length 4. Correct answer is 1 (just [100]).
✅ The Corrected Version
function minSubArrayLen(target, nums) {
let left = 0, sum = 0, minLen = Infinity;
for (let right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum >= target) { // FIXED: Keep shrinking until invalid
minLen = Math.min(minLen, right - left + 1); // Update result while valid
sum -= nums[left];
left++;
}
}
return minLen === Infinity ? 0 : minLen;
}Tooling & visualization tips
- Paper Tracing: Draw the array. Use two fingers. Move them exactly as your code dictates.
- Debugger: Set a conditional breakpoint on
right. - Invariant Check: Ask yourself: "At line X, is
sumexactly equal to the sum ofnums[left...right]?"
Summary
Shrinking bugs usually come from under-shrinking (using if) or updating state out of order. Stick to the standard pattern: Expand -> While Invalid Shrink -> Update Result.
Next Step:
Even if your logic is right, you might still get the length wrong by one index. Fix that with Sliding Window Off-by-One Errors.
Ready to Practice This Pattern?
Apply this pattern with LeetCopilot's AI-powered hints, notes, and mock interviews. Transform your coding interview preparation today.
