Maximum Length Substring With Two Occurrences - Problem

Given a string s, return the maximum length of a substring such that it contains at most two occurrences of each character.

A substring is a contiguous sequence of characters within a string.

Input & Output

Example 1 — Basic Case
$ Input: s = "bcbbbcba"
Output: 4
💡 Note: The optimal substring is "bcbb" with b appearing 2 times and c appearing 1 time, giving length 4
Example 2 — All Same Character
$ Input: s = "aaaa"
Output: 2
💡 Note: Since we can have at most 2 occurrences of each character, the longest valid substring is "aa" with length 2
Example 3 — All Different Characters
$ Input: s = "abcde"
Output: 5
💡 Note: All characters are different, so the entire string is valid with length 5

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters

Visualization

Tap to expand
Maximum Length Substring With Two Occurrences INPUT String s = "bcbbbcba" b 0 c 1 b 2 b 3 b 4 c 5 b 6 a 7 Constraint: Each character can appear at most 2 times in substring Input Values: s = "bcbbbcba" Length: 8 ALGORITHM STEPS 1 Sliding Window Use two pointers: left, right 2 Track Frequency Count each char in window 3 Shrink if Invalid Move left if count > 2 4 Update Max Length Track maximum valid window Best Window: "bcbb" or "cbba" b c b b b c b a Freq: b=2, c=1 (valid) Window length = 4 OK - All counts <= 2 FINAL RESULT Maximum valid substring length 4 Valid Substrings of Length 4: "bcbb" (indices 0-3) "cbba" (indices 5-8) Both have max 2 of each char Output: 4 Key Insight: The sliding window technique with character frequency tracking allows us to efficiently find the longest valid substring. When any character count exceeds 2, shrink the window from the left until valid again. Time Complexity: O(n) | Space Complexity: O(1) - fixed character set TutorialsPoint - Maximum Length Substring With Two Occurrences | Optimal Solution (Sliding Window)
Asked in
Google 15 Facebook 12 Amazon 8
21.4K Views
Medium Frequency
~15 min Avg. Time
823 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen