Longest Substring With At Most K Distinct Characters
The problem
Given a string s and an integer k.Find the length of the longest substring with at most k distinct characters.
Input : s = "aababbcaacc" , k = 2 Output : 6 Explanation : The longest substring with at most two distinct characters is "aababb". The length of the string 6.
Input : s = "abcddefg" , k = 3 Output : 4 Explanation : The longest substring with at most three distinct characters is "bcdd". The length of the string 4.
Input : s = "abccab" , k = 4
- 1 <= s.length <= 105
- 1 <= k <= 26
cpp
class Solution {
public:
int kDistinctChar(string& s, int k) {
//your code goes here
}
};java
class Solution {
public int kDistinctChar(String s, int k) {
//your code goes here
}
}python
class Solution:
def kDistinctChar(self, s, k):
#your code goes herejavascript
class Solution {
kDistinctChar(s, k) {
//your code goes here
}
}csharp
public class Solution
{
public int kDistinctChar(string s, int k)
{
//your code goes here
}
}go
func kDistinctChar(s string, k int) int {
}Stuck? Show a way to structure it+
- 01Expand the right boundary and increment that character's frequency.
- 02While the number of distinct characters exceeds k, shrink from the left.
- 03Record the largest valid window after restoring the invariant.
- 04Handle k equal to zero without admitting a non-empty window.
Reference answer
Then expect these follow-ups
How would you count substrings with exactly k distinct characters?
Tests: window transformation
Why does each pointer move at most n times?
Tests: complexity
Free to read · better with Enzo
Practice this out loud with Enzo
Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.
Next question