FastPrepLongest Stretch With At Most K Different Letters
Problems/Longest Stretch With At Most K Different Letters

Longest Stretch With At Most K Different Letters

Adobe logoAdobe● MediumFULLTIMEPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: Two Adobe first-round reports carry this task: the longest stretch of a string that holds at most k different characters. One candidate kept a count per character in a moving window, and the interviewer then had them walk a sample input by hand. The other already knew the problem and coded the usual two-pointer answer.

Neither report gives limits or examples, so ours are: 1 to 5 * 10^4 lowercase letters, k from 0 to 26 (k = 0 gives 0), and new examples.

The judged task matches the reports at about 95%.

You are given a string s and an integer k. Find the longest stretch of consecutive characters in s that uses at most k different letters, and return its length.

  • A letter that repeats inside the stretch counts as one different letter.
  • If no letter is allowed (k = 0), only the empty stretch qualifies, so the answer is 0.

Function

longestKDistinct(s: String, k: int) → int

Examples

Example 1

s = "abaccc"k = 2return = 4

The substring "accc" (indexes 2 to 5) has only 'a' and 'c', and its length is 4. Any longer substring would also contain the 'b' at index 1 together with 'a' and 'c', which is 3 different letters.

Example 2

s = "zzyyxx"k = 5return = 6

The whole string uses only 3 different letters, which is fewer than k = 5, so the answer is its full length, 6.

Example 3

s = "xyz"k = 0return = 0

With k = 0 no letter may appear, so only the empty substring qualifies. The answer is 0.

Constraints

  • 1 <= s.length <= 5 * 10^4
  • s contains only lowercase English letters.
  • 0 <= k <= 26

More Adobe problems

  • Evaluate a Parenthesized Integer ExpressionPHONE SCREEN · Seen Oct 2026
  • All Elements of Two BSTs in OrderPHONE SCREEN · Seen Aug 2026
  • Rotate an Array In PlaceOA · PHONE SCREEN · Seen Aug 2026
All Adobe interview questionsSee Adobe hiring insights
Saved
public int longestKDistinct(String s, int k) {
    // Write your code here.
}
Checking account…