Swap For Longest Repeated Character Substring - Problem
Given a string
A substring is a contiguous sequence of characters within the string. After the optional swap, you want to find the longest possible substring where all characters are identical.
Example: In string
Note: You don't have to perform a swap if the original string already contains the optimal solution.
text, you can perform at most one swap of any two characters in the string. Your goal is to maximize the length of the longest substring containing repeated characters.A substring is a contiguous sequence of characters within the string. After the optional swap, you want to find the longest possible substring where all characters are identical.
Example: In string
"ababa", swapping positions 1 and 2 gives "aabba", creating a substring "aa" of length 2.Note: You don't have to perform a swap if the original string already contains the optimal solution.
Input & Output
example_1.py โ Basic case
$
Input:
"ababa"
โบ
Output:
3
๐ก Note:
We can swap positions 0 and 2 to get "abaab", then positions 2 and 4 to get "aabab". But optimally, swap positions 1 and 3 to get "aabaa", giving us a substring "aaa" of length 3.
example_2.py โ All same characters
$
Input:
"aaaa"
โบ
Output:
4
๐ก Note:
The string already consists of repeated characters, so no swap is needed. The entire string has length 4.
example_3.py โ Two character types
$
Input:
"aaabbaaa"
โบ
Output:
6
๐ก Note:
We can swap one 'b' with an 'a' to create a longer sequence of 'a's. For example, swap position 3 (first 'b') with position 4 (second 'b') doesn't help, but we can rearrange to get "aaaabaaa" giving us 4 consecutive 'a's, or "aaaaaaabb" giving us 6 consecutive 'a's by moving characters optimally.
Constraints
- 1 โค text.length โค 105
- text consists of lowercase English letters only
- You can perform at most one swap operation
Visualization
Tap to expand
Understanding the Visualization
1
Analyze Original
Count each character type and find current longest repeated substring
2
For Each Character
Use sliding window to find longest achievable sequence for each character type
3
Simulate Swap
Allow at most one 'wrong' character in window that could be swapped out
4
Find Maximum
Return the maximum achievable length across all character types
Key Takeaway
๐ฏ Key Insight: Rather than actually performing swaps, we can simulate their effect using a sliding window that allows at most one character that could be 'swapped out' to achieve our target character sequence.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code