Swap For Longest Repeated Character Substring — LeetCode 1156 Python Solution

MediumHash TableStringSliding Window
Problem
#1156
Reading time
3 min

The problem

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

Example

Input
text = "ababa"
Output
3
Explanation
We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa" with length 3.

Python solution

Python
class Solution:
    def maxRepOpt1(self, text: str) -> int:
        cnt = Counter(text)
        n = len(text)
        ans = i = 0
        while i < n:
            j = i
            while j < n and text[j] == text[i]:
                j += 1
            l = j - i
            k = j + 1
            while k < n and text[k] == text[i]:
                k += 1
            r = k - j - 1
            ans = max(ans, min(l + r + 1, cnt[text[i]]))
            i = j
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(C) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1156. Swap For Longest Repeated Character Substring is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1156. Swap For Longest Repeated Character Substring?
LeetCode 1156. Swap For Longest Repeated Character Substring is rated Medium on LeetCode.
What is the time complexity of LeetCode 1156. Swap For Longest Repeated Character Substring?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1156. Swap For Longest Repeated Character Substring?
The Python solution on this page uses O(C) auxiliary space.
What topics does LeetCode 1156. Swap For Longest Repeated Character Substring cover?
LeetCode 1156. Swap For Longest Repeated Character Substring is tagged Hash Table, String and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview