FastPrepLongest Substring with At Most K Distinct Characters
Problems/Longest Substring with At Most K Distinct Characters

Longest Substring with At Most K Distinct Characters

Goldman Sachs logoGoldman Sachs● MediumFULLTIMEONSITE INTERVIEW

Updated Sep 2026

QuestionFunctionExamplesConstraints

Problem statement

Source note: A Goldman Sachs superday report links the exact Longest Substring with At Most K Distinct Characters exercise. The report omits the portable signature and bounds; this practice version is an approximately 99% match.

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 Onsite Interview questions

  • Knight Probability in ChessboardONSITE INTERVIEW · Seen Nov 2026
  • Best Average Student ScorePHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
  • Meeting RoomsPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
  • Minimum Meeting Rooms Without a Sweep LineONSITE INTERVIEW · Seen Oct 2026
  • First Non-Repeating CharacterPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
  • Root of the Largest TreePHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
  • Dungeon HealthONSITE INTERVIEW · Seen Sep 2026
  • Insert, Delete, And Get Random In Constant TimeONSITE INTERVIEW · Seen Sep 2026
  • Least Recently Used CacheONSITE INTERVIEW · Seen Sep 2026
  • Staircase Search In A Sorted MatrixONSITE INTERVIEW · Seen Sep 2026

Similar questions at other companies

  • Longest Substring with At Most K Distinct CharactersAmazon Web Services · ONSITE INTERVIEW
  • Longest Substring Without Repeating CharactersOracle · ONSITE INTERVIEW
  • Longest Substring Without Repeating CharactersSalesforce · ONSITE INTERVIEW
  • Longest Substring Without Repeating CharactersMicrosoft · ONSITE INTERVIEW
  • Longest Substring Without Repeating CharactersGoogle · ONSITE INTERVIEW
  • Longest Substring Without Repeating CharactersAmazon · ONSITE INTERVIEW
  • Longest Substring Without Repeating CharactersInfosys · ONSITE INTERVIEW
  • Longest Substring Without Repeating CharactersOmnissa · ONSITE INTERVIEW
  • Longest Substring Without Repeating CharactersBloomberg LP · PHONE SCREEN · ONSITE INTERVIEW
  • Longest Substring Without Repeating CharactersBank of America · ONSITE INTERVIEW
See Goldman Sachs hiring insights
Saved
class Solution {
    public int longestSubstringAtMostKDistinct(String s, int k) {
      // write your code here
    }
}
Checking account…