Practice › Sliding Window
Longest Substring with At Most K Distinct Characters
Medium · Sliding Window · Asked at Google, Amazon, Meta, Microsoft
Print the length of the longest substring of s that contains at most k distinct characters.
Input
First line: the string s (lowercase letters). Second line: k.
Output
The length of the longest such substring.
Constraints
- 1 ≤ |s| ≤ 10^5
- 1 ≤ k ≤ 26
Grow the window on the right and count each letter. While the window has more than k distinct letters, shrink it from the left. Track the largest window seen.
Example 1
Input
eceba 2
Output
3
Example 2
Input
aa 1
Output
2
Hints
- Use two pointers for a window [l, i].
- Keep a count of each letter in the window and how many letters have a non-zero count.
- When the window has more than k distinct letters, move l right until it is valid again.
Approach
Expand the right end one letter at a time; if that letter's count goes from 0 to 1, the number of distinct letters grows. While it exceeds k, remove s[l] from the window (if its count drops to 0, distinct shrinks) and move l forward. After each step the window is the longest valid one ending at i, so track the maximum length. Each pointer only moves forward.
Complexity: O(n) time · O(26) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
int k;
cin >> s >> k;
int cnt[26] = {0};
int distinct = 0, best = 0, l = 0;
for (int i = 0; i < (int) s.size(); i++) {
if (cnt[s[i] - 'a']++ == 0) distinct++;
while (distinct > k)
if (--cnt[s[l++] - 'a'] == 0) distinct--;
best = max(best, i - l + 1);
}
cout << best << "\n";
return 0;
}Python solution
import sys
s = sys.stdin.readline().strip()
k = int(sys.stdin.readline())
cnt = [0] * 26
distinct = best = l = 0
for i, ch in enumerate(s):
c = ord(ch) - 97
if cnt[c] == 0:
distinct += 1
cnt[c] += 1
while distinct > k:
d = ord(s[l]) - 97
cnt[d] -= 1
if cnt[d] == 0:
distinct -= 1
l += 1
if i - l + 1 > best:
best = i - l + 1
print(best)Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine().trim();
int k = Integer.parseInt(br.readLine().trim());
int[] cnt = new int[26];
int distinct = 0, best = 0, l = 0;
for (int i = 0; i < s.length(); i++) {
if (cnt[s.charAt(i) - 'a']++ == 0) distinct++;
while (distinct > k)
if (--cnt[s.charAt(l++) - 'a'] == 0) distinct--;
best = Math.max(best, i - l + 1);
}
System.out.println(best);
}
}Solve Longest Substring with At Most K Distinct Characters online · All practice problems