Longest K Unique Characters Substring
A medium Sliding Window problem included in Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Sliding Window
- Sheets
- 1
- Core for
- 5 roles
- Platform
- GeeksforGeeks
The problem
Given a string, find the length of the longest substring that contains at most k distinct characters.
Example 1
- Input
- s = "eceba", k = 2
- Output
- 3
- Why
- The longest substring with at most 2 distinct characters is 'ece'.
Example 2
- Input
- s = "aabbcc", k = 2
- Output
- 4
- Why
- The longest substring with at most 2 distinct characters is 'aabb' or 'bbcc'.
Constraints
- 1 <= s.length <= 10^4
- s consists of lowercase English letters
- 1 <= k <= 26
How to think about it
Updated 2026-09-09As the right pointer expands, character diversity never decreases. When the count of unique characters exceeds k, the current window is invalid and cannot be extended further; only shrinking from the left can reduce distinct characters back within the allowed budget.
Approaches, worst first
Examine all substrings
time O(n^2) · space O(k)
Generate every substring, insert characters into a set, and find the maximum length among those with at most k distinct entries. Performs quadratic redundant scans.
Sliding window with frequency mapWrite this one
time O(n) · space O(k)
Maintain character counts in a hash map or fixed array while expanding right. When map size exceeds k, advance left and decrement counts until a character is fully removed from the map, then record maximum valid window size.
Where people lose marks · 3
- Failing to remove the character key completely from the frequency table when its count reaches zero, causing map size to falsely overreport distinct characters.
- Failing to check whether k is greater than or equal to the total number of distinct characters in the string, in which case the whole string is valid.
- Using a fixed-size 26 array but failing to maintain a separate unique character counter, forcing an O(26) scan on every single window expansion.
The theory behind it
Sliding Window — the ground this problem stands on. All Sliding Window problems
What Sliding Window is
A sliding window is an adjustable magnifying lens placed over a continuous segment of a sequence. Rather than recalculating metrics for every potential subsection from scratch, the window expands rightward by absorbing fresh elements and contracts leftward to expel stale entries. Only data currently framed within the window borders contributes to the active calculation.
When to reach for it
Reach for a sliding window when a question asks for the longest, shortest, or optimal contiguous subarray or substring matching a constraint. Key signals include fixed window sizes like maximum sum across k consecutive values, or dynamic criteria like finding the shortest substring holding all target characters. If the target subset must form an unbroken continuous run, window mechanics replace repetitive segment rescanning.
How the pattern works
Maintain two boundary indices, left and right, defining the active interval alongside a running state accumulator. In each step, expand the right boundary to incorporate the incoming element into state totals. When current state violates the designated problem constraints, increment the left boundary while deducting departing values until validity is restored. Update your tracking metric, whether minimum window length or maximum score, only during valid intervals.
What each operation costs
| Operation | Time |
|---|---|
| slide window across full array length | O(n) |
| update running aggregate per incoming element | O(1) |
| auxiliary window frequency map storage | O(k) |
What usually goes wrong with Sliding Window
- Shrinking the left border using an if statement instead of a while loop, allowing invalid window conditions to persist across iterations.
- Updating optimum results before validating window legality, recording illegal states that contain duplicate items or violate length requirements.
- Forgetting to decrement left element frequencies or remove empty keys from tracking maps when advancing the left boundary forward.
Which roles need this problem
Sliding Window is a core topic for these 5 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 10 more roles, including SDE / Backend Engineer, Data Engineer, ML Engineer.
Companies that have asked it
Tags taken from the problem's own GeeksforGeeks page — not a copied list.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Sliding Window problems
Problem set and role mapping as of .