Swap For Longest Repeated Character Substring - Problem

You are given a string text. You can swap two of the characters in the text.

Return the length of the longest substring with repeated characters.

A substring is a contiguous sequence of characters within a string. After swapping two characters, you need to find the longest substring where all characters are the same.

Input & Output

Example 1 — Basic Case
$ Input: text = "ababa"
Output: 3
💡 Note: We can swap the second 'b' with the last 'a' to get "aabaa", then the longest substring with repeated characters is "aaa" with length 3.
Example 2 — All Same Characters
$ Input: text = "aaaa"
Output: 4
💡 Note: All characters are already the same, so no swap is needed. The entire string "aaaa" has length 4.
Example 3 — Two Different Characters
$ Input: text = "abab"
Output: 3
💡 Note: We can swap one 'b' with one 'a' to get "aaab" or "abaa", giving us a longest repeated substring of length 3.

Constraints

  • 1 ≤ text.length ≤ 1000
  • text consists of only lowercase English letters

Visualization

Tap to expand
Swap For Longest Repeated Character Substring INPUT String: text = "ababa" a idx 0 b idx 1 a idx 2 b idx 3 a idx 4 Character Counts: 'a': 3 'b': 2 Character Groups: 'a' at: [0, 2, 4] 'b' at: [1, 3] Goal: Find longest substring after 1 swap ALGORITHM STEPS 1 Count Characters Store frequency of each char 2 Find Consecutive Groups Group same consecutive chars 3 Check Merge Options Groups separated by 1 char 4 Track Maximum Keep best result found Example: Merge 'a' groups Before: a b a b a After: a a a b b swap 3 consecutive 'a's FINAL RESULT Optimal swap found: a a a b b Length = 3 Output: 3 Explanation: Swap 'b' at idx 1 with 'a' at idx 4 "ababa" ---> "aabba" Longest repeated: "aaa" = 3 OK Key Insight: For optimal solution, consider: (1) extending a single group by 1 if extra chars exist, (2) merging two groups of same char separated by exactly one different char. The max length is bounded by total count of that character. Time: O(n), Space: O(1) using sliding window. TutorialsPoint - Swap For Longest Repeated Character Substring | Optimal Solution
Asked in
Google 25 Facebook 18 Amazon 15
23.0K Views
Medium Frequency
~25 min Avg. Time
890 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