Tutorialspoint
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
StringsTCS (Tata Consultancy Services)Shopify
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Use a sliding window approach with two pointers (left and right).
 Step 2: Maintain a dictionary to keep track of the characters in the current window and their frequencies.
 Step 3: Expand the window by moving the right pointer and adding characters to the dictionary.
 Step 4: When the number of distinct characters exceeds k, shrink the window by moving the left pointer and removing characters from the dictionary as necessary.
 Step 5: Keep track of the maximum window size seen so far.
 Step 6: Return the maximum window size as the result.
 Step 7: Handle edge cases like empty strings or k = 0.

Submitted Code :