O22

Longest Substring with At Most K Distinct Characters

Mid / Senior Engineer
Target Time: 25 - 35 Minutes
Type: NUMERIC

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) -> int

Input & 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 <= 50

Example Execution Walkthrough

s = "eceba", k = 2
"ece" contains 2 distinct characters ('e', 'c') -> length 3

Example Test Scenarios (3)

Example 1
Input:["eceba",2]
Expected Output:3
Example 2: Tek Karakter
Input:["aa",1]
Expected Output:2
Example 3: k=0
Input:["a",0]
Expected Output:0
Loading Python Editor...
Input Parameters
[
  "eceba",
  2
]
Expected Output
3