Why does "if (need[c] > 0)" condition cause incorrect result in sliding window algorithm? [closed]

1 day ago 1
ARTICLE AD BOX

Why does adding need[c] > 0 condition break my sliding window algorithm for Minimum Window Substring?

I am solving LeetCode 76 Minimum Window Substring. I found something very strange.

Problem Description: Given strings s and t, find the minimum window in s that will contain all the characters in t.

Test case:

s = "ADOBECODEBANC" t = "ABC" Expected output: "BANC"

Strange behavior:

When I use the sliding window algorithm WITHOUT checking need[c] > 0, it returns "BANC" correctly. When I add the condition "if (need[c] > 0)", it returns "ADOBEC" which is wrong.

The need[c] > 0 condition should be harmless because:

For characters not in t, need[c] == 0 These characters never affect num or maxnum So skipping ne[c]++ for them should not change anything

But the test results show it does change the result. Why?

I verified this on both local Java and LeetCode, and both show the same incorrect result with need[c] > 0.

Here is the relevant code section with the need[c] > 0 check:

while (right < y.length) { char c = y[right]; right++; if (need[c] > 0) { ne[c]++; if (ne[c] == need[c]) { num++; } } while (num == maxnum) { if (right - left < finum) { finum = right - left; minleft = left; } char mm = y[left]; if (ne[mm] == need[mm]) { num--; } ne[mm]--; left++; } }
Read Entire Article