Leetcode #2730: Find the Longest Semi-Repetitive Substring
In this guide, we solve Leetcode #2730 Find the Longest Semi-Repetitive Substring in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given a digit string s that consists of digits from 0 to 9. A string is called semi-repetitive if there is at most one adjacent pair of the same digit.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: String, Sliding Window
Intuition
We are looking for a contiguous region that satisfies a constraint, which is a classic sliding-window signal.
Expanding and shrinking the window lets us maintain validity without restarting the scan.
Approach
Grow the window with a right pointer, and shrink from the left only when the constraint is violated.
Track the best window as you go to keep the solution linear.
Steps:
- Expand the right end of the window.
- While invalid, move the left end to restore constraints.
- Update the best window found.
Python Solution
class Solution:
def longestSemiRepetitiveSubstring(self, s: str) -> int:
ans, n = 1, len(s)
cnt = j = 0
for i in range(1, n):
cnt += s[i] == s[i - 1]
while cnt > 1:
cnt -= s[j] == s[j + 1]
j += 1
ans = max(ans, i - j + 1)
return ans
Complexity
The time complexity is , where is the length of the string. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.