
Problem
Solution
Submissions
Longest Substring with at Most k Distinct Characters
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C# program to find the length of the longest substring of a string s that contains at most k distinct characters.
Example 1
- Input: s = "eceba", k = 2
- Output: 3
- Explanation:
- The substring "ece" contains 2 distinct characters, 'e' and 'c'.
Example 2
- Input: s = "aa", k = 1
- Output: 2
- Explanation:
- The substring "aa" contains 1 distinct character, 'a'.
Constraints
- 1 <= s.length <= 5 * 10^4
- 0 <= k <= 50
- s consists of lowercase English letters
- Time Complexity: O(n) where n is the length of the string
- Space Complexity: O(min(k, m)) where m is the size of the character set
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a sliding window approach to track the substring
- Maintain a dictionary to keep track of the frequency of each character in the current window
- When adding a new character would exceed k distinct characters, shrink the window from the left
- Keep track of the maximum window size seen so far
- The solution should iterate through the string once