Magicsheet logo

Swap For Longest Repeated Character Substring

Medium
97.5%
Updated 6/1/2025

Swap For Longest Repeated Character Substring

What is this problem about?

The Swap For Longest Repeated Character Substring interview question asks you to find the length of the longest substring consisting of the same character that can be obtained by performing at most one swap between any two characters in the string. For example, in "ababa", you could swap the last 'a' with the 'b' in the middle to get "aaaa b", making the longest repeated substring 4.

Why is this asked in interviews?

This "Medium" difficulty problem is often asked by Microsoft and Google to test sliding window techniques and hash table usage. It requires you to consider multiple scenarios: extending a block of identical characters by one (if another instance of that character exists elsewhere) or joining two blocks of the same character that are separated by exactly one different character. It evaluates your ability to handle complex edge cases and window transitions.

Algorithmic pattern used

The primary algorithmic pattern is the Sliding Window combined with a Frequency Hash Table. First, count the total occurrences of each character in the string. Then, identify all contiguous segments of the same character. For each character, you look for two adjacent segments separated by a single character. If they are the same character, you can potentially join them by swapping a third instance of that character from elsewhere in the string.

Example explanation

String: aaabaaa

  • Segments of 'a': [0, 2] (length 3) and [4, 6] (length 3).
  • They are separated by 'b' at index 3.
  • Total 'a's in string = 6.
  • Since we have exactly 6 'a's in these two segments, we can swap the 'b' with an 'a' from the end of one of the segments. Max length = 6. If the string was aaabaaa...a, we could join the two segments and have an extra 'a' to swap in, potentially making a longer sequence.

Common mistakes candidates make

A common error is forgetting that you can only swap one pair of characters. Another mistake is not checking if there is actually a character available to "swap in" from outside the current window. Candidates often fail to handle the case where a character appears in only one segment but can still be extended by one if there are more of that character elsewhere in the string.

Interview preparation tip

To prepare for the Swap For Longest Repeated Character Substring coding problem, master the Sliding Window interview pattern. Practice breaking a string down into "runs" or segments. This makes it much easier to reason about joining segments. Also, ensure you are comfortable using a frequency map to keep track of total counts of characters.

Similar Questions