Find the Longest Semi-Repetitive Substring - Problem

You are given a digit string s consisting of digits from 0 to 9. Your task is to find the longest semi-repetitive substring within this string.

A string is considered semi-repetitive if it contains at most one adjacent pair of the same digit. Think of it as allowing only one "double" digit occurrence in the entire substring.

Examples of semi-repetitive strings:

  • "0010" - has one adjacent pair (00)
  • "002020" - has one adjacent pair (00)
  • "0123" - has no adjacent pairs
  • "2002" - has one adjacent pair (00)
  • "54944" - has one adjacent pair (44)

Examples of NON semi-repetitive strings:

  • "00101022" - has two adjacent pairs: (00) and (22)
  • "1101234883" - has two adjacent pairs: (11) and (88)

Return the length of the longest semi-repetitive substring of s.

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "52233"
โ€บ Output: 4
๐Ÿ’ก Note: The longest semi-repetitive substring is "5223" with length 4. It contains exactly one adjacent duplicate pair (22).
example_2.py โ€” No Duplicates
$ Input: s = "5494"
โ€บ Output: 4
๐Ÿ’ก Note: The entire string "5494" is semi-repetitive as it has no adjacent duplicate pairs. The length is 4.
example_3.py โ€” Single Character
$ Input: s = "1"
โ€บ Output: 1
๐Ÿ’ก Note: A single character string is always semi-repetitive. The length is 1.

Constraints

  • 1 โ‰ค s.length โ‰ค 1000
  • s consists only of digits from '0' to '9'
  • The string is guaranteed to be non-empty

Visualization

Tap to expand
1 1 2 3 3 4 5Valid Window: 1 2 3 3Length: 4 (1 duplicate pair)leftright๐ŸŽฏ Key Insight: Sliding window with at most 1 duplicate pair constraintTime: O(n) | Space: O(1)
Understanding the Visualization
1
Start Small
Begin with a minimal window of size 1
2
Expand Greedily
Keep expanding the window as long as you have โ‰ค 1 duplicate pair
3
Contract When Needed
When you exceed 1 duplicate pair, shrink from the left
4
Track Maximum
Remember the largest valid window size you've seen
Key Takeaway
๐ŸŽฏ Key Insight: Use sliding window to maintain a substring with at most one adjacent duplicate pair, expanding greedily and contracting only when necessary.
Asked in
Google 15 Amazon 8 Meta 6 Microsoft 4
28.5K Views
Medium Frequency
~18 min Avg. Time
892 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