LeetCode solutions

1261. Swap For Longest Repeated Character Substring

My accepted Python solution to LeetCode problem 1261, Swap For Longest Repeated Character Substring, running in 23ms.

  • Difficulty: Medium
  • Python
  • Runtime 23ms
  • Memory 18.7MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 23ms, memory 18.7MB, accepted 2026-01-02.

python
class Solution:
    def maxRepOpt1(self, text: str) -> int:
        from collections import Counter
        
        count = Counter(text)
        
        # Group consecutive characters
        groups = []
        i = 0
        while i < len(text):
            j = i
            while j < len(text) and text[j] == text[i]:
                j += 1
            groups.append((text[i], j - i))
            i = j
        
        result = 0
        
        for i, (char, length) in enumerate(groups):
            # Case 1: just this group (possibly extend by 1 if there are more chars)
            result = max(result, min(length + 1, count[char]))
            
            # Case 2: merge two groups separated by single char
            if i + 2 < len(groups) and groups[i + 1][1] == 1 and groups[i + 2][0] == char:
                merged_len = length + groups[i + 2][1]
                # Can we add one more from elsewhere?
                if count[char] > merged_len:
                    merged_len += 1
                result = max(result, merged_len)
        
        return result

Source