Problem Description
Given a string text, you are allowed to swap two characters in the string exactly once. Determine the length of the longest substring that can be formed consisting of one repeated character, after performing at most one swap.
Key Insights
- Count the frequency of each character.
- Split the string into groups of consecutive identical characters.
- For each group, consider extending its length by swapping a character from elsewhere (if additional occurrences exist).
- Check for the case where two groups of the same character are separated by exactly one different character; if so, merging them (with a swap) might yield a longer repeated substring.
- Use a greedy approach to iterate through the groups and update the maximum achievable length.
Space and Time Complexity
Time Complexity: O(n) because we traverse the string to group characters and iterate over groups. Space Complexity: O(n) in the worst-case scenario (when the string has alternating characters) for storing groups and frequency counts.
Solution
The solution uses a two-step process:
- First, count the total occurrences of each character.
- Second, create a list of groups where each group contains a character and its consecutive count. Then, for each group, determine the maximum length achievable by:
- Using a swap to extend the current group if there are additional characters available elsewhere.
- Merging two adjacent groups of the same character when they are separated by exactly one different character.
The algorithm then iterates through all groups and maintains the maximum length found.