Find the Longest Semi-Repetitive Substring - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "52233"
Output: 4
💡 Note: The longest semi-repetitive substring is "5223" with length 4. It has exactly one adjacent pair (2,2).
Example 2 — No Adjacent Pairs
$ Input: s = "5494"
Output: 4
💡 Note: The entire string "5494" has no adjacent pairs, so it's completely semi-repetitive with length 4.
Example 3 — Multiple Pairs
$ Input: s = "1111"
Output: 2
💡 Note: Any substring longer than 2 would have more than one adjacent pair. Maximum is "11" with length 2.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of digits from 0 to 9

Visualization

Tap to expand
Find Longest Semi-Repetitive SubstringSemi-repetitive = at most 1 adjacent pair of same digits52233Input: "52233""5223" - Valid (1 adjacent pair)"52233" - Invalid (2 adjacent pairs)Output: 4 (length of "5223")
Understanding the Visualization
1
Input
String with digits 0-9
2
Process
Find substrings with ≤1 adjacent pair
3
Output
Length of longest valid substring
Key Takeaway
🎯 Key Insight: Use sliding window to efficiently find the longest substring with at most one adjacent pair
Asked in
Google 25 Amazon 15
8.5K Views
Medium Frequency
~15 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen