Maximum Length Substring With Two Occurrences - Problem
Maximum Length Substring With Two Occurrences
You're given a string
Think of it as finding the longest "balanced" portion of text where no character becomes too repetitive. For example, in the string
Goal: Return the length of the longest valid substring
Input: A string
Output: An integer representing the maximum substring length
You're given a string
s, and your task is to find the maximum length of any substring where each character appears at most twice.Think of it as finding the longest "balanced" portion of text where no character becomes too repetitive. For example, in the string
"abcaba", the entire string is valid since each character ('a', 'b', 'c') appears at most 2 times, giving us a maximum length of 6.Goal: Return the length of the longest valid substring
Input: A string
s containing lowercase English lettersOutput: An integer representing the maximum substring length
Input & Output
example_1.py โ Basic Case
$
Input:
s = "bcbbbcba"
โบ
Output:
4
๐ก Note:
The optimal substring is "bcbb" with frequencies: b=3 (invalid), c=1. Actually, "cbbb" won't work either. The correct answer is "bcbb" -> "cbb" (length 3) or "bcb" (length 3) or "bbc" (length 3) or "cbbc" (length 4) where c=2, b=2. So maximum length is 4.
example_2.py โ All Characters Valid
$
Input:
s = "abcaba"
โบ
Output:
6
๐ก Note:
The entire string is valid since character frequencies are: a=3 (invalid). Wait, let me recalculate: a appears at positions 0,3,5 (3 times), b appears at positions 1,4 (2 times), c appears at position 2 (1 time). Since 'a' appears 3 times, we need a substring. The longest valid substring is "bcab" or "caba" or "abca" (length 4) where no character appears more than twice.
example_3.py โ Single Character
$
Input:
s = "aa"
โบ
Output:
2
๐ก Note:
The string "aa" has character frequency: a=2, which satisfies the constraint of at most 2 occurrences per character.
Constraints
- 1 โค s.length โค 105
- s consists of lowercase English letters only
- Each character can appear at most 2 times in a valid substring
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Window
Start with an empty window at the beginning of the string
2
Expand Right
Keep adding characters to the right side of the window
3
Monitor Frequencies
Track how many times each character appears in the current window
4
Shrink When Invalid
When any character appears 3+ times, remove characters from the left
5
Track Maximum
Remember the largest valid window size encountered
Key Takeaway
๐ฏ Key Insight: The sliding window technique efficiently maintains a valid substring by expanding right and contracting left as needed, ensuring each character appears at most twice while tracking the maximum valid length.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code