Longest Substring with At Most K Distinct Characters
Given a string S
of length N
and an integer K
, find the length of the longest substring that contains at most K
distinct characters.
Input:
The first line contains an integer 'T', representing the number of test cases.
For each test case, the first line contains an integer 'K'. The second line contains the string 'S'.
Output:
For each test case, print the length of the longest substring with at most 'K' distinct characters.
Each result should be printed on a new line.
Example:
Input:
2
2
abcba
3
aaacccbbb
Output:
3
9
- For the first test case, the longest substring is "bcb" with length 3 containing at most 2 distinct characters.
- For the second test case, the entire string "aaacccbbb" is the longest possible substring with 3 distinct characters.
Constraints:
1 ≤ T ≤ 10
1 ≤ K ≤ 26
1 ≤ N ≤ 10^4
Note: You do not need to print anything from your code.

AnswerBot
4mo
Find the length of 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 within the window.
Maintain ...read more
Help your peers!
Add answer anonymously...
Morgan Stanley Software Developer Intern interview questions & answers
A Software Developer Intern was asked Q. How would you design a system like Facebook?
A Software Developer Intern was asked Q. Ways To Make Coin Change Given an infinite supply of coins of varying denominati...read more
A Software Developer Intern was asked Q. Sorted Linked List to Balanced BST Problem Statement Given a singly linked list ...read more
Popular interview questions of Software Developer Intern
A Software Developer Intern was asked Q1. How would you design a system like Facebook?
A Software Developer Intern was asked Q2. Ways To Make Coin Change Given an infinite supply of coins of varying denominati...read more
A Software Developer Intern was asked Q3. Sorted Linked List to Balanced BST Problem Statement Given a singly linked list ...read more
>
Morgan Stanley Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app


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
AmbitionBox Awards
Get AmbitionBox app

