O22
Longest Substring with At Most K Distinct Characters
Problem Statement & Objective
Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.
Function Signature (Python)
longest_substring_k_distinct(s: str, k: int) -> intInput & Output Contract
Output Rule:Length of longest substring with <= k distinct characters. If k = 0, returns 0.
System Constraints
1 <= s.length <= 5 * 10^4
0 <= k <= 50Example Execution Walkthrough
s = "eceba", k = 2
"ece" contains 2 distinct characters ('e', 'c') -> length 3Example Test Scenarios (3)
Example 1
Input:
["eceba",2]Expected Output:
3Example 2: Tek Karakter
Input:
["aa",1]Expected Output:
2Example 3: k=0
Input:
["a",0]Expected Output:
0