Maximum Length Substring With Two Occurrences

Easy Arrays & Hashing Sliding Window · Variable Original on LeetCode

Maximum Length Substring With Two Occurrences is a easy arrays & hashing problem solved with the sliding window · variable pattern. The best approach, optimal (sliding window), runs in O(n) time and O(1) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force up.

Problem

Given a string s of lowercase letters, find the length of the longest substring (a contiguous piece of s) in which no letter occurs more than twice.

Return that length.

Examples

Example 1

Input
s = "abacbcab"
Output
6
Why
"abacbc" uses a, b and c exactly twice each; any 7-letter window holds some letter three times.

Example 2

Input
s = "zzzz"
Output
2
Why
Any window longer than 2 contains z at least three times.

Example 3

Input
s = "pqrqpz"
Output
6
Why
No letter appears more than twice, so the whole string qualifies.

Constraints

  • 2 <= s.length <= 100
  • s contains only lowercase English letters.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute forceO(n²)O(1)
Optimal (sliding window)O(n)O(1)

1Brute force

TimeO(n²)Up to n extensions for each of n starting points.
SpaceO(1)A fixed 26-slot count array.

Try every starting index. Extend the substring one letter at a time, counting letters, and stop as soon as some letter appears a third time. The longest valid stretch seen is the answer.

  1. For each start i, reset a 26-slot count array.
  2. For j from i onward, increment count[s[j]]; if it becomes 3, stop extending.
  3. Otherwise update best with j - i + 1.
class Solution {
    public int maximumLengthSubstring(String s) {
        int n = s.length(), best = 0;
        for (int i = 0; i < n; i++) {
            int[] cnt = new int[26];
            for (int j = i; j < n; j++) {
                int c = s.charAt(j) - 'a';
                cnt[c]++;
                if (cnt[c] > 2) break;
                best = Math.max(best, j - i + 1);
            }
        }
        return best;
    }
}

2Optimal (sliding window)

TimeO(n)Each index enters and leaves the window at most once.
SpaceO(1)Only 26 counters.

Keep a window [left, right] where every letter appears at most twice. Add s[right]; if its count becomes 3, shrink from the left until that count drops back to 2. After each step the window is valid, so compare its length with the best.

  1. left = 0, best = 0, counts all zero.
  2. For each right: increment count of s[right].
  3. While that count is above 2: decrement count of s[left] and move left forward.
  4. best = max(best, right - left + 1).
class Solution {
    public int maximumLengthSubstring(String s) {
        int[] cnt = new int[26];
        int left = 0, best = 0;
        for (int right = 0; right < s.length(); right++) {
            int c = s.charAt(right) - 'a';
            cnt[c]++;
            while (cnt[c] > 2) {
                cnt[s.charAt(left) - 'a']--;
                left++;
            }
            best = Math.max(best, right - left + 1);
        }
        return best;
    }
}

Edge cases to test

  • The whole string already qualifies
  • One letter repeated many times: the answer is 2
  • The best window sits at the very end of the string

Hints

Hint 1

Fix a start index and extend to the right while no letter goes above two.

Hint 2

When a letter reaches three inside a window, the left edge must move past an earlier copy of it. Keep counts and slide the left edge.

FAQ

What is the best time complexity for Maximum Length Substring With Two Occurrences?

Optimal (sliding window) runs in O(n) time and O(1) extra space. Each index enters and leaves the window at most once.

Which pattern does Maximum Length Substring With Two Occurrences use?

It is a arrays & hashing problem that uses the sliding window · variable pattern. Other problems with the same pattern: Minimum Size Subarray Sum, Count of Subarrays with Product Less Than K, Longest Repeating Character Replacement.

Is there a brute force solution for Maximum Length Substring With Two Occurrences?

Yes. Brute force takes O(n²) time and O(1) space. Try every starting index.

Which edge cases should I test for Maximum Length Substring With Two Occurrences?

The whole string already qualifies; One letter repeated many times: the answer is 2; The best window sits at the very end of the string.