#2730

Find the Longest Semi-Repetitive Substring

Medium
StringSliding WindowSliding WindowTwo Pointers
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

Using a sliding window approach allows us to efficiently find the longest semi-repetitive substring without generating all possible substrings. This method keeps track of the number of adjacent pairs as we expand and contract our window.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two pointers (left and right) to represent the current window and a variable to count adjacent pairs.
  2. 2Step 2: Expand the right pointer to include new characters in the window, updating the count of adjacent pairs.
  3. 3Step 3: If the count of adjacent pairs exceeds 1, move the left pointer to reduce the size of the window until the count is valid again.
  4. 4Step 4: Keep track of the maximum length of valid windows during the process.
solution.py20 lines
1# Full working Python code
2
3def longest_semi_repetitive_substring(s):
4    left = 0
5    max_length = 0
6    adjacent_count = 0
7    n = len(s)
8
9    for right in range(n):
10        if right > 0 and s[right] == s[right - 1]:
11            adjacent_count += 1
12        while adjacent_count > 1:
13            if s[left] == s[left + 1]:
14                adjacent_count -= 1
15            left += 1
16        max_length = max(max_length, right - left + 1)
17    return max_length
18
19# Example usage
20print(longest_semi_repetitive_substring('52233'))

Complexity note: The time complexity is O(n) because we only traverse the string once with the two pointers. The space complexity is O(1) since we are using a fixed amount of extra space.

  • 1Understanding the definition of semi-repetitive is crucial to solving the problem correctly.
  • 2Using a sliding window technique can significantly optimize the solution by avoiding unnecessary checks.

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