Problem Description
Given a string s consisting of lowercase English letters, return the maximum length of a substring such that it contains at most two occurrences of each character.
Key Insights
- The problem is a sliding window problem where we maintain a window that satisfies the constraint (each character appears at most twice).
- Use a hash table (or dictionary) to track the count of each character in the current window.
- Expand the window with the right pointer until a character count exceeds two.
- When the constraint is violated, move the left pointer to reduce counts until the window becomes valid.
- Update the maximum length during valid window intervals.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string, because each element is processed at most twice. Space Complexity: O(1), as the frequency dictionary only stores counts for 26 lowercase English letters.
Solution
We use the sliding window approach by maintaining two pointers (left and right) and a frequency map (or hash table) to keep track of the count of each character in the current window. Start by moving the right pointer to include new characters. If adding a new character leads to its count exceeding 2, increment the left pointer until the count is corrected. During each valid window, update the maximum window length if needed. This ensures we check all potential substrings while keeping the solution efficient.