Longest Substring with At Most K Distinct Characters
Medium Sliding Window
s is a string of letters and digits, and k is a whole number.
A substring is a run of characters that sit next to each other in s, with none skipped. It may use at most k different characters, repeating each as often as it likes. Upper case and lower case letters are different characters, so a and A count as two.
Return the length of the longest substring that follows this rule. When k is 0 no character is allowed, so the answer is 0.
Example 1
Input: s = "xxyzzzyx", k = 2
Output: 5
The substring yzzzy has two different characters and is 5 long; adding the x on either side would make three.
Example 2
Input: s = "AaAaBb", k = 2
Output: 4
Example 3
Input: s = "k9k9k", k = 5
Output: 5
Constraints
1 ≤ s.length ≤ 10⁵sholds only letters (a–z,A–Z) and digits (0–9)0 ≤ k ≤ 62
Solve it here
Write it in Python, Java or C++, run it on your own cases, and submit against hidden tests.
More Sliding Window
- Longest Substring Without Repeating CharactersAI round · Medium
- Sliding Window MaximumAI round · Hard
- Minimum Window SubstringAI round · Hard
- Minimum Size Subarray SumAI round · Medium
- Longest Repeating Character ReplacementMedium