Maximum Length Substring With Two Occurrences (LeetCode 3090): Solution and Explanation

Easy
Hash table
String
Sliding window

Slide a window across the string and keep a count for each letter inside it. When a letter shows up a third time, move the left edge forward until it is back to two, then record the window length.

Intuition

If a substring is valid, every shorter substring inside it is valid too. That is the property that lets a sliding window work: the best window ending at right starts at the smallest valid left, and that left never moves backwards.

Adding one character can only break the rule for that one letter. So after adding s[right], the only thing to check is whether its count went above 2.

To fix it, drop characters from the left until one copy of that letter has left the window. Other letters' counts only go down while doing this, so they stay valid.

Approach: Sliding window with letter counts

  1. Create count of size 26, and set left = 0, best = 0.
  2. For each right, increment count[s[right]].
  3. While that count is greater than 2, decrement count[s[left]] and increment left.
  4. Set best = max(best, right - left + 1).
  5. Return best.

Step-by-step example

s = "bcbbbcba"
  1. right = 0..2: "bcb" is fine (b twice, c once), best = 3.
  2. right = 3: a third b. Drop s[0] = b, left = 1. Window "cbb", length 3.
  3. right = 4: a third b again. Drop c and b, left = 3. Window "bb", length 2.
  4. right = 5: "bbc", length 3. right = 6: third b, drop s[3], left = 4, window "bcb".
  5. right = 7: "bcba" has length 4, new best. Answer: 4.

Code: Python, Java, C++

1class Solution:
2    def maximumLengthSubstring(self, s: str) -> int:
3        count = [0] * 26
4        left = 0
5        best = 0
6        for right, ch in enumerate(s):
7            c = ord(ch) - ord('a')
8            count[c] += 1
9            while count[c] > 2:
10                count[ord(s[left]) - ord('a')] -= 1
11                left += 1
12            best = max(best, right - left + 1)
13        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each index enters the window once and leaves it at most once.

Space

O(1)

A fixed array of 26 counters.

Other approaches

Brute force over all substrings (time O(n^2), space O(1))

For each start, extend the end while counting letters and stop at the first third copy. With n at most 100 this is fast enough, but it does not scale.

Common mistakes

  • Checking every letter's count after each step. Only the letter that just entered can exceed 2.
  • Using if instead of while when shrinking. The first character removed may be a different letter, so several steps can be needed.
  • Updating best before the window is fixed, which counts an invalid window.

Frequently asked questions

Why does only the new letter need checking?

Before adding s[right], the window was valid. Adding one character raises only that letter's count, so it is the only one that can reach 3.

How does this generalise?

Replace 2 with any limit k and the same code solves the longest subarray with at most k copies of each value, as in Length of Longest Subarray With at Most K Frequency.

What is the time and space complexity?

O(n) time, since both pointers only move forward, and O(1) space for 26 counters.