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
Be the first one to answer
Add answer anonymously...
Lifesight Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

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

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter