#1156

Swap For Longest Repeated Character Substring

Medium
Hash TableStringSliding WindowHash MapSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a sliding window technique to find the longest substring of repeated characters while considering the possibility of a single swap. This approach is efficient and avoids unnecessary swaps.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a hashmap to count the frequency of each character in the string.
  2. 2Step 2: Use a sliding window to track the longest substring of repeated characters, allowing for one character to be different (the one we can swap).
  3. 3Step 3: Calculate the maximum length of the substring based on the counts from the hashmap.
solution.py9 lines
1# Full working Python code
2
3def longest_repeated_char_substring(text):
4    from collections import Counter
5    count = Counter(text)
6    max_count = max(count.values())
7    n = len(text)
8    return min(n, max_count + 1)
9

Complexity note: The time complexity is O(n) because we only traverse the string a couple of times (once for counting and once for finding the max), making it efficient for large inputs.

  • 1Swapping allows us to potentially increase the length of repeated characters.
  • 2Using a hashmap to count character frequencies helps in optimizing the search for the longest substring.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.