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 Substring INPUT String s = "52233" 5 i=0 2 i=1 2 i=2 3 i=3 3 i=4 pair 1 pair 2 Semi-Repetitive Rule: At most ONE adjacent pair of same digits allowed "5223" has 1 pair: OK "52233" has 2 pairs: NOT OK ALGORITHM STEPS 1 Sliding Window Use two pointers: left, right 2 Count Adjacent Pairs Track pairs in current window 3 Shrink When pairs > 1 Move left until pairs <= 1 4 Update Max Length max = max(max, right-left+1) Window Progression: [5] len=1 [5,2] len=2 [5,2,2] len=3 pair:1 [5,2,2,3] len=4 pair:1 [5,2,2,3,3] pair:2 SHRINK [2,2,3,3] pair:2 SHRINK FINAL RESULT Longest Semi-Repetitive: 5 2 2 3 "5223" - Only 1 adjacent pair Output: 4 Verification: "5223" contains: 1 adjacent pair (22) - OK Length = 4 characters Key Insight: The sliding window expands to include characters, tracking adjacent duplicate pairs. When pairs exceed 1, shrink from left until valid. This ensures O(n) time complexity by visiting each element at most twice. TutorialsPoint - Find the Longest Semi-Repetitive Substring | Optimal Solution O(n)
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