Longest Sub-string with at most K Distinct Characters

You are given string S of length N, and an integer K. Your task is to find the length of the longest substring that contains at most K distinct characters.

Input Format:
The first line contains an Integer 'T' which denotes the number of test cases/queries to be run. 
Then the test cases follow. 

The first line of input for each test case/query contains an integer K.

The second line of input for each test case/query contains a string S.
Output Format:
For each test case, print the length of the longest substring that contains at most K distinct characters.

Output for every test case will be printed in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 10
1 <= K <= 26
1 <= N <= 10^4

Time Limit: 1sec
CodingNinjas
author
2y
Brute Force
  • We will generate all the substrings using 2 nested for loops and we will have a ‘CHECK’ function which returns true if the number of distinct character in the substring is less than equal t...read more
CodingNinjas
author
2y
Improved version
  • We will run a loop from i = 0 to i = N - 1 where i will be starting position of the substring and j = i to j = N - 1 where j will be the end position of the substring. Before starting ...read more
CodingNinjas
author
2y
Using Binary Search
  • We will be doing the binary search on the answer that is the length of the substring where LOW = 1 and HIGH = N will be the range of our answer and we will have a variable ANS = 0 t...read more
CodingNinjas
author
2y
Optimal Approach
  • Create a hash table or a frequency array lets name it ‘FREQ’ and initialize all the position with 0.
  • We will run a loop from i = 0 to i = N - 1 which will be the right boundary of the s...read more
Add answer anonymously...
Morgan Stanley 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
Get AmbitionBox app

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