mediumStringsPattern: Sliding Window

Longest Substring with K Unique Characters Solution

Problem Statement

Given a string and an integer k, find the length of the longest substring that contains exactly k unique characters.

Examples

Example 1:
Input:s = 'abcba', k = 2
Output:2
Explanation: The longest substrings with 2 unique characters are 'ab', 'bc', 'cb', and 'ba' with length 2.
Example 2:
Input:s = 'abcdabc', k = 3
Output:6
Explanation: The longest substring with 3 unique characters is 'abcdab' with length 6.

Constraints

  • 1 <= k <= 26
  • 1 <= s.length <= 10^5
  • s consists of only lowercase English letters
Time: O(n) Space: O(k)
The optimized approach uses a sliding window technique with a frequency map to track the unique characters in the current window, achieving a time complexity of O(n).

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.