Problem · String

Longest Substring with At Most K Distinct Characters

Learn this problem
MediumGoldman Sachs logoGoldman SachsFULLTIMEONSITE INTERVIEW

Problem statement

Given a string s and an integer k, return the maximum length of a contiguous substring containing at most k distinct characters.

Return 0 when k is zero or s is empty.

Function

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

Examples

Example 1

s = "eceba"k = 2return = 3

The substring ece has two distinct characters.

Example 2

s = "aa"k = 1return = 2

The entire string uses one distinct character.

Constraints

  • 0 <= s.length <= 200000
  • 0 <= k <= 200000
  • s contains printable ASCII characters.

More Goldman Sachs problems

drafts saved locally
public int longestSubstringAtMostKDistinct(String s, int k) {
  // write your code here
}
s"eceba"
k2
expected3
checking account