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. For example, "0010", "002020", "0123", "2002", and "54944" are semi-repetitive while the following are not: "00101022" (adjacent same digit pairs are 00 and 22), and "1101234883" (adjacent same digit pairs are 11 and 88).
Return the length of the longest semi-repetitive substring of s.
Example 1:
Input:s = "52233"
Output:4
Explanation:
The longest semi-repetitive substring is "5223". Picking the whole string "52233" has two adjacent same digit pairs 22 and 33, but at most one is allowed.
Example 2:
Input:s = "5494"
Output:4
Explanation:
s is a semi-repetitive string.
Example 3:
Input:s = "1111111"
Output:2
Explanation:
The longest semi-repetitive substring is "11". Picking the substring "111" has two adjacent same digit pairs, but at most one is allowed.
Problem summary: 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. For example, "0010", "002020", "0123", "2002", and "54944" are semi-repetitive while the following are not: "00101022" (adjacent same digit pairs are 00 and 22), and "1101234883" (adjacent same digit pairs are 11 and 88). Return the length of the longest semi-repetitive substring of s.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Sliding Window
Example 1
"52233"
Example 2
"5494"
Example 3
"1111111"
Step 02
Core Insight
What unlocks the optimal approach
Since n is small, we can just check every substring, and if the substring is semi-repetitive, maximize the answer with its length.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2730: Find the Longest Semi-Repetitive Substring
class Solution {
public int longestSemiRepetitiveSubstring(String s) {
int ans = 1, n = s.length();
for (int i = 1, j = 0, cnt = 0; i < n; ++i) {
cnt += s.charAt(i) == s.charAt(i - 1) ? 1 : 0;
for (; cnt > 1; ++j) {
cnt -= s.charAt(j) == s.charAt(j + 1) ? 1 : 0;
}
ans = Math.max(ans, i - j + 1);
}
return ans;
}
}
// Accepted solution for LeetCode #2730: Find the Longest Semi-Repetitive Substring
func longestSemiRepetitiveSubstring(s string) (ans int) {
ans = 1
for i, j, cnt := 1, 0, 0; i < len(s); i++ {
if s[i] == s[i-1] {
cnt++
}
for ; cnt > 1; j++ {
if s[j] == s[j+1] {
cnt--
}
}
ans = max(ans, i-j+1)
}
return
}
# Accepted solution for LeetCode #2730: Find the Longest Semi-Repetitive Substring
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
// Accepted solution for LeetCode #2730: Find the Longest Semi-Repetitive Substring
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #2730: Find the Longest Semi-Repetitive Substring
// class Solution {
// public int longestSemiRepetitiveSubstring(String s) {
// int ans = 1, n = s.length();
// for (int i = 1, j = 0, cnt = 0; i < n; ++i) {
// cnt += s.charAt(i) == s.charAt(i - 1) ? 1 : 0;
// for (; cnt > 1; ++j) {
// cnt -= s.charAt(j) == s.charAt(j + 1) ? 1 : 0;
// }
// ans = Math.max(ans, i - j + 1);
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #2730: Find the Longest Semi-Repetitive Substring
function longestSemiRepetitiveSubstring(s: string): number {
const n = s.length;
let ans = 1;
for (let i = 1, j = 0, cnt = 0; i < n; ++i) {
cnt += s[i] === s[i - 1] ? 1 : 0;
for (; cnt > 1; ++j) {
cnt -= s[j] === s[j + 1] ? 1 : 0;
}
ans = Math.max(ans, i - j + 1);
}
return ans;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(k)
Approach Breakdown
BRUTE FORCE
O(n × k) time
O(1) space
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
SLIDING WINDOW
O(n) time
O(k) space
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Shortcut: Each element enters and exits the window once → O(n) amortized, regardless of window size.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Shrinking the window only once
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.