Longest Substring with K Distinct Characters

You are provided with a string S of length N, consisting of lowercase English alphabet letters, and a positive integer K.

Your task is to determine the maximum length of a substring of S that contains at most K distinct characters.

Example:

Input:
S = "bacda"
K = 3
Output:
4
Explanation:

The substrings that have at most 3 distinct characters include: "bac", "acd", "acda". The longest one is "acda" with a length of 4, hence the result is 4.

Constraints:

  • 1 <= T <= 10
  • 1 <= K <= 26
  • 1 <= N <= 10^4
  • All characters in the string are lowercase English alphabet letters.
  • Time Limit: 1 sec
AnswerBot
4mo

Find the longest substring with at most K distinct characters in a given string.

  • Use a sliding window approach to keep track of the characters and their counts in the substring.

  • Maintain a hashmap to st...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Lifesight

Q. Sliding Window Maximum Problem Statement You are given an array/list of integers...read more
Q. Combination Sum Problem Statement Given an array of distinct positive integers A...read more
Q. Cycle Detection in Undirected Graph Problem Statement You are provided with an u...read more
Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits