You solved the problem. The logic is sound. But the output is 4 and the expected answer is 3.
You change right - left + 1 to right - left. Now it works.
But do you know why?
Off-by-one errors are the silent killers of coding interviews. Guessing +1 or -1 until it passes tests shows the interviewer you don't understand your own code.
In this guide, we will fix your boundary logic once and for all.
TL;DR — The Golden Rules of Indexing
- Inclusive Window (
[left, right]): Length =right - left + 1. - Exclusive Window (
[left, right)): Length =right - left. - Prefix Sums: Often 1-indexed (Size N+1).
- When in doubt: Test with a single element
[0, 0]. Result should be 1.
Why off-by-one happens in sliding window
The confusion usually stems from two things:
- Indexing: Are arrays 0-indexed or 1-indexed? (Usually 0).
- Inclusivity: Is the window
[left, right](inclusive) or[left, right)(exclusive)?
In the standard Sliding Window pattern using a for loop for right:
leftpoints to the first element of the window.rightpoints to the last element of the window (currently being added).
Therefore, the window is Inclusive-Inclusive [left, right].
The Golden Formula
If your window includes both nums[left] and nums[right]:
Window Length = right - left + 1
Proof:
- Window:
[index 2, index 2](single element). - Length:
2 - 2 + 1 = 1. Correct. - Window:
[index 2, index 4](elements 2, 3, 4). - Length:
4 - 2 + 1 = 3. Correct.
Code pattern examples
1. Max Length Window (e.g., Longest Substring)
for (let right = 0; right < n; right++) {
// ... expand ...
while (invalid) { /* shrink */ }
// Window is [left, right] and is VALID
maxLen = Math.max(maxLen, right - left + 1);
}2. Fixed Size Window (Size K)
for (let right = 0; right < n; right++) {
// ... add nums[right] ...
// Window size is exactly right - left + 1
if (right - left + 1 === k) {
// Record result
// Shrink one step to maintain size
left++;
}
}Reference points: start=0 vs start=1
In some algorithms (like Prefix Sums), we often use a 1-based size or an extra padding element.
- Standard Sliding Window: Always 0-indexed.
left = 0,right = 0. - Prefix Sum Array: Often size
N+1. Be careful not to mix these indices.
Edge cases that trigger off-by-one
1. Empty Input
- Input:
[] - Loop:
rightfrom 0 to -1 (doesn't run). - Result: Returns initial value (usually 0). Safe.
2. Single Element
- Input:
[5] - Loop: Runs once.
right=0,left=0. - Length:
0 - 0 + 1 = 1. Safe.
3. The "Result Update" Location
If you update the result inside the shrink loop (common for "Minimum Window" problems), ensure you calculate length before you increment left.
while (sum >= target) {
// Correct: Update BEFORE shrinking
minLen = Math.min(minLen, right - left + 1);
sum -= nums[left];
left++;
}Testing strategy: how to detect boundary errors quickly
Don't wait for the full test suite. Run these mental checks:
- The "Single Element" Check: Does my formula return 1 for a single item window?
- The "Empty" Check: Does it crash on empty string?
- The "Full Array" Check: If the whole array is the window, is length
N? (N-1 - 0 + 1 = N).
FAQ
Q: Why do some solutions use right - left?
A: Those solutions likely use an exclusive upper bound (where right points to the next element to be processed, not the current one). While valid, it is confusing to mix with 0-indexed arrays. We recommend the inclusive approach.
Q: What if I start right at 1?
A: You will need to manually handle the 0-th element initialization. It adds boilerplate code and increases the risk of bugs. Start at 0 whenever possible.
Pro Tip: Muscle Memory
Don't re-derive the formula every time. Commit this template to muscle memory:
for (right = 0; right < n; right++)- Window is
[left, right](Inclusive). - Length is
right - left + 1.
Summary
Stop guessing.
- If
rightis the index of the current element: Length = right - left + 1. - If
rightis the index of the next element (exclusive): Length = right - left.
Stick to the standard Inclusive pattern (right - left + 1) for 99% of LeetCode problems.
Next Steps:
You have mastered the Sliding Window!
Ready to Practice This Pattern?
Apply this pattern with LeetCopilot's AI-powered hints, notes, and mock interviews. Transform your coding interview preparation today.
