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...
Amazon Software Developer Intern interview questions & answers
A Software Developer Intern was asked 3mo agoQ. What is the code to calculate the distance between two nodes in a binary tree?
A Software Developer Intern was asked 4mo agoQ. Given a tree, find its diameter (the longest path between two nodes in the tree)...read more
A Software Developer Intern was asked 4mo agoQ. For a given array, how would you count the number of inversions?
Popular interview questions of Software Developer Intern
A Software Developer Intern was asked 3mo agoQ1. What is the code to calculate the distance between two nodes in a binary tree?
A Software Developer Intern was asked 4mo agoQ2. For a given array, how would you count the number of inversions?
A Software Developer Intern was asked 4mo agoQ3. Given a tree, find its diameter (the longest path between two nodes in the tree)...read more
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

