Skip to main content

Guidelines

There are three parts to every sliding window problem:

  • Operation for calculating the property of the window (sum, count of characters)
  • Operation to make an invalid window valid again (move the start a bit to the right)
  • Recording the best so far result of the property (shortest/longest window)

Template to use:

for(int i = l1; i < l2; ++i){
freqMap[s2.charAt(i) - 'a']--;
freqMap[s2.charAt(i-l1) - 'a']++;
if(found(freqMap)) return true;
}
// useful for counting letters of interest
for(char c: t.toCharArray()) freqMap[c]++;
int start = 0, end = 0, cnt = l2;
while(end < l1){
if(freqMap[s.charAt(end++)]-- > 0) --cnt;
while(cnt == 0){
// record the better window if possible
if(freqMap[s.charAt(start++)]++ == 0) ++cnt;
}
}
while(j < nums.length){
windowSum += nums[j++]; // go to the right (move end to the right)

while(windowSum >= target){ // try shortening the window by moving the start of it until it become invalid
minLength = Math.min(minLength, j - i);
windowSum -= nums[i++];
}
}
while(j < fruits.length){
map.put(fruits[j], j);

while(map.size() > 2){ // invalid window, move the start further in array (shrink the window)
int minIndex = map.values().stream().min(Integer::compare).get(); // find the right index to remove the character from
map.remove(fruits[minIndex]);
i = minIndex + 1;
}

maxFruits = Math.max(maxFruits, j - i + 1); //record the result
++j; // keep going as far to right as possible (expanding the window)
}

Useful mapping for other types of problems containing a larger set of different characters:

  • int[26] for Letters 'a' - 'z' or 'A' - 'Z'
  • int[128] for ASCII
  • int[256] for Extended ASCII

Calculation over all windows of size k Sliding Window Maximum