
Mastering Fixed Sliding Window in C++ (LeetCode 1876)
Today I solved a beautiful Sliding Window problem that perfectly demonstrates how fixed-size windows work. Problem: Count substrings of size 3 with all distinct characters. Problem Understanding We are given a string s. We need to count how many substrings of length 3 contain all distinct characters. Example Input: s = "xyzzaz" Valid substrings of length 3: "xyz" "yzz" (z repeated) "zza" "zaz" Output: 1 Why Sliding Window? Since the substring size is fixed (3), this is a Fixed Sliding Window problem. Instead of generating all substrings (which would be inefficient), we: Maintain a window of size 3. Use a frequency map to track character counts. Slide the window one step at a time. Check if all characters are distinct. Approach Step 1 -> Initialize first window (size 3) Add first 3 characters into a hashmap. Step 2 -> Check validity If all frequencies are 1 → count it. Step 3 -> Slide the window For every next position Remove left character Add new right character Check validity again R
Continue reading on Dev.to
Opens in a new tab




