Skip to content

Instantly share code, notes, and snippets.

@decagondev
Last active April 23, 2025 21:19
Show Gist options
  • Select an option

  • Save decagondev/48517b95b7f953fb90f60e51fda1e7ed to your computer and use it in GitHub Desktop.

Select an option

Save decagondev/48517b95b7f953fb90f60e51fda1e7ed to your computer and use it in GitHub Desktop.

PROBLEM 10: Longest Substring with At Most K Distinct Characters

Problem Statement

Given a string s and an integer k, return the length of the longest substring that contains at most k distinct characters.

Concepts Covered

  • Sliding Window
  • HashMap for Character Frequency
  • Edge Case Handling

Examples

Input: s = "eceba", k = 2
Output: 3
Explanation: The substring is "ece" with length 3.

Input: s = "aa", k = 1
Output: 2

Starter Code

def length_of_longest_substring_k_distinct(s: str, k: int) -> int:
    # Implement your solution here
    pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment