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.

Be the first one to answer
Add answer anonymously...
American Express Software Developer Intern 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