Longest Substring with At Most K Distinct Characters
Updated
Problem statement
Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.
A substring is a run of neighbouring characters of s. Uppercase and lowercase letters are different characters, so a and A count as two. When k = 0, no character is allowed, so the answer is 0.
Function
lengthOfLongestSubstringKDistinct(s: String, k: int) → intExamples
Example 1
s = "eceba"k = 2return = 3The substring "ece" uses only e and c, so it has 2 distinct characters and length 3. Both substrings of length 4 have too many: "eceb" has three distinct characters and "ceba" has four.
Example 2
s = "aa"k = 1return = 2The whole string uses one character, a, so the answer is its length, 2.
Example 3
s = "AaAbBbb"k = 2return = 4Uppercase and lowercase are different characters. "AaA" uses A and a and has length 3, and "bBbb" uses b and B and has length 4. Every longer substring contains at least three of A, a, b and B.
Constraints
1 <= s.length <= 5 * 10^40 <= k <= 50sconsists of English letters only (lowercase and uppercase).
More Amazon Web Services Onsite Interview questions
Similar questions at other companies
- Longest Substring Without Repeating CharactersOracle · ONSITE INTERVIEWOracle interview questions
- Longest Substring Without Repeating CharactersSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Longest Substring Without Repeating CharactersMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Longest Substring Without Repeating CharactersGoogle · ONSITE INTERVIEWGoogle interview questions
- Longest Substring Without Repeating CharactersAmazon · ONSITE INTERVIEW
- Longest Substring Without Repeating CharactersInfosys · ONSITE INTERVIEWInfosys interview questions
- Longest Substring Without Repeating CharactersOmnissa · ONSITE INTERVIEWOmnissa interview questions
- Longest Substring Without Repeating CharactersBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Longest Substring with At Most K Distinct CharactersGoldman Sachs · ONSITE INTERVIEWGoldman Sachs interview questions
- Longest Substring Without Repeating CharactersBank of America · ONSITE INTERVIEWBank of America interview questions