The Core Difference

PropertySliding WindowPrefix Sum
All elements non-negative?βœ… Worksβœ… Works
Negative elements?❌ Breaksβœ… Works
State monotonic when expanding?βœ… RequiredNot needed
SpaceO(1) to O(n)O(n)
TimeO(n)O(n)

The One Rule

Sliding window works when moving the left pointer always makes the window β€œmore valid.” The moment a single element can both increase AND decrease the state β€” use Prefix Sum.


Same Problem β€” Different Solution

930. Binary Subarrays With Sum

Binary array (only 0s and 1s) β†’ adding element only increases sum β†’ Sliding Window works.

// Sliding Window approach
int atMost(vector<int>& A, int S) {
    if (S < 0) return 0;
    int res = 0, sum = 0, j = 0;
    for (int i = 0; i < A.size(); i++) {
        sum += A[i];
        while (sum > S) sum -= A[j++];
        res += i - j + 1;
    }
    return res;
}
int numSubarraysWithSum(vector<int>& A, int S) {
    return atMost(A, S) - atMost(A, S - 1);
}

560. Subarray Sum Equals K

Can have negative numbers β†’ Sliding Window breaks β†’ use Prefix Sum.

// Prefix Sum + HashMap approach
int subarraySum(vector<int>& nums, int k) {
    unordered_map<int, int> mp;
    mp[0] = 1;
    int psum = 0, count = 0;
    for (int i = 0; i < nums.size(); i++) {
        psum += nums[i];
        count += mp[psum - k];
        mp[psum]++;
    }
    return count;
}

Decision Flowchart

Subarray problem?
β”œβ”€β”€ Fixed window size k β†’ Fixed Sliding Window
└── Variable window
    β”œβ”€β”€ All elements positive / binary?
    β”‚   β”œβ”€β”€ Count subarrays β†’ atMost(K) - atMost(K-1)
    β”‚   β”œβ”€β”€ Max length β†’ shrink while invalid
    β”‚   └── Min length β†’ shrink while valid
    └── Negative elements possible?
        β”œβ”€β”€ Count / Length β†’ Prefix Sum + HashMap
        └── Divisibility β†’ Prefix Sum + Remainder map

Common Traps

"Looks like sliding window" but isn't

ProblemWhy SW failsReal solution
Subarray Sum = K (with negatives)Adding element can increase OR decrease sumPrefix Sum + HashMap
Contiguous Array (equal 0s and 1s)Replace 0β†’-1, now has negativesPrefix Sum + HashMap
Longest Palindromic SubstringNo monotonic window propertyExpand from center
Longest Continuous Subarray, abs diff ≀ limitNeed both max AND min of windowMonotonic Deque