Given a string
Output: 3
Explanation: The substring "ece" has 2 distinct characters and length 3.
Output: 2
Explanation: The substring "aa" has 1 distinct character and length 2.
Output: 4
Explanation: The substrings "aabb" or "bbcc" have 2 distinct characters and length 4.
Constraints:
1 <= s.length <= 5 * 104 0 <= k <= 50
Contents
Solution - Sliding Window with Frequency Map Complexity Analysis
This is a classic dynamic sliding window problem. We expand the window by moving
Implementation steps:
-
Use a
HashMap<Character, Integer> to track the frequency of each character in the window. -
Expand the window by adding
s.charAt(right) to the map. -
When
map.size() > k , shrink the window from the left: decrement the count ofs.charAt(left) and remove it from the map when its count reaches 0. -
After shrinking, update
maxLen with the current window size.
Trace through Example 1: s = "eceba", k = 2
| right | char | map | left | window | maxLen |
|---|---|---|---|---|---|
| 0 | e | {e:1} | 0 | "e" | 1 |
| 1 | c | {e:1,c:1} | 0 | "ec" | 2 |
| 2 | e | {e:2,c:1} | 0 | "ece" | 3 |
| 3 | b | {e:1,c:1,b:1} → shrink → {e:1,b:1} | 2 | "eb" | 3 |
| 4 | a | {e:1,b:1,a:1} → shrink → {b:1,a:1} | 3 | "ba" | 3 |
-
Time complexity: O(n) — each character is added to the window once by
right and removed at most once byleft . Total operations: O(2n) = O(n). -
Space complexity: O(k) — the frequency map holds at most
k + 1 entries at any point (before shrinking).