Data Structures & Algorithms (Sliding Window): Find the Longest Semi-Repetitive Substring

February 10, 2026

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.

Playground: Leetcode 2730


Basic Intution

A substring becomes invalid when it already contains one adjacent equal pair and we encounter a new digit that matches the digit immediately before it, forming a second pair.

basic-intution


Naive Approach: Nested Loops

Use an outer loop to iterate over each digit, treating it as the starting point of a substring.

Use an inner loop to explore all substrings starting at that position, expanding one character at a time and stopping when the substring becomes invalid (i.e., contains more than one adjacent equal pair).

Algorithm

1. Initializa a variable: "maxLength" to track the length of the longest valid 
   substring found so far.

2. Iterate over each starting index:
    3. Initialize a variable: "containsAdjacentPair" to track if the current substring 
       already contains an adjacent equal pair.
    4. Expand the current substring one "digit" at a time:
        5. If the current "digit" equals the digit immediately before it:
            6. If "containsAdjacentPair" is already true, stop expanding the current 
                substring and move to the next starting index, since any larger 
                substring starting at the same index will also be invalid.
            7. Otherwise, set "containsAdjacentPair" to "true".
        8. Update "maxLength" if necessary.

9. Return "maxLength".

Implementation

Sample inputs
1public int longestSemiRepetitiveSubstring(String s) {
2
3 //1. Initializa a variable to track the length of the longest valid substring found so far.
4 int maxLength = 1;
5
6 //2. Iterate over each starting index:
7 for (int i = 0; i < s.length() - 1; i++) {
8
9 // 3. Initialize a variable to track if the current substring already contains an adjacent equal pair.
10 boolean containsAdjacentPair = false;
11
12 // 4. Expand the current substring one digit at a time:
13 for (int j = i + 1; j < s.length(); j++) {
14
15 char digit = s.charAt(j);
16 char previousDigit = s.charAt(j-1);
17 // 5. If the current digit equals the digit immediately before it:
18 if (digit == previousDigit) {
19 /* 6. If an adjacent equal pair is observed before, stop expanding the
20 * current substring and move to the next starting index.
21 */
22 if (containsAdjacentPair) {
23 break;
24 } else {
25 // 7. Otherwise, mark adjacent equal pair observed before as true.
26 containsAdjacentPair = true;
27 }
28 }
29 // 8. Update max length if necessary.
30 maxLength = Math.max(maxLength, j - i + 1);
31
32 }
33
34 }
35
36 // 9. Return max length.
37 return maxLength;
38
39}
Ready

Press Play or Step. Each start grows until a second adjacent pair appears.

Input string
j
j
j
j
j
5
2
2
3
3
i
i
i
i
i
0
1
2
3
4
'?'=='?'→?
placeholder
i= —
j= —
containsAdjacentPair= false
maxLength= 1
Current window
Longest substring1
0/44

Time Complexity

In the worst-case scenario, i.e., when the string contains all distinct characters, we'll end up exploring all possible substrings.

The outer loop iterates for each starting index. For each ith iteration, the inner loop executes (n-i-1) times, where i ranges from 0 to (n-1).

Since each inner-loop iteration performs only constant-time operations, the time complexity depends on the total number of iterations.

= (n-0) + (n-1) + (n-2) + ... + (n - (n-2)) + (n - (n-1))
= n + (n-1) + (n-2) + ... + 2 + 1
= [n x (n+1)] / 2

Since, the total number of iterations are of the order n^2, the overall time complexity is O(n^2).

Space Complexity

We use only a few variables to track the length of the longest valid substring and whether an adjacent equal pair has already been observed.

Since the algorithm does not use any additional data structures and the number of variables remains constant regardless of the input size, the overall space complexity is O(1).


Key Observations


  1. If a substring [i...j] represents the longest valid substring starting at index i, we don't need to explore all substrings ending before j and starting between (i+1) and j, since they will always be shorter than the current substring [i..j].

key-observation-1

  1. Once the substring [i...j] becomes invalid, we don't need to restart exploration from i. Instead, we can keep the right pointer fixed at j and move the left pointer forward until the current substring becomes valid again.

key-observation-2


Suitable Approach: Sliding Window

Use two pointers, left and right, to maintain a sliding window representing the current substring under consideration.

  1. Expand the window by moving right pointer forward and updating the count of adjacent equal pairs if current character is equal to the previous character.

  2. If the count of adjacent equal pairs becomes greater than one, start shrinking the window by moving left pointer forward and reducing the count if current character is equal to the next character.

Algorithm

1. Initialize:
    a. Two pointers, "left" and "right", to represent the boundaries of the current substring.
    b. A variable, "adjacentEqualPairCount", to track the number of adjacent equal pairs in the 
       current substring.
    c. A variable, "result", to track the length of longest valid substring found so far. 

2. Expand the current window by moving "right" one character at a time:
    3. If the current character is equal to the immediately preceding character, increment 
       "adjacentEqualPairCount" by 1.
    4. If the "adjacentEqualPairCount" exceeds 1:
            a. If the character at "left" is equal to the next character, decrement 
               "adjacentEqualPairCount" by 1.
            b. Move "left" forward to shrink the current window.
    5. Once the window becomes valid, update "result" if the current window length is greater 
       than the maximum length found so far.

6. Return "result".

Implementation

Sample inputs
1
public int longestSemiRepetitiveSubstring(String s) {
2
3
// 1. Initialize
4
int left = 0;
5
int adjacentEqualPairCount = 0;
6
int maxLength = 1;
7
8
// 2. Expand the current window
9
for (int right = 0; right < s.length(); right++) {
10
// 3. Update the count of adjacent equal pairs.
11
if (right > 0 && s.charAt(right) == s.charAt(right - 1)) adjacentEqualPairCount++;
12
13
// 4. Shrink the current window to make it valid.
14
while (adjacentEqualPairCount > 1) {
15
if (s.charAt(left) == s.charAt(left + 1)) adjacentEqualPairCount--;
16
left++;
17
}
18
19
// 5. Update the length of the longest valid substring if necessary.
20
maxLength = Math.max(maxLength, right - left + 1);
21
22
23
}
24
25
// 6. Return the length of the longest valid substring.
26
return maxLength;
27
28
}
Ready
Press Play or Step. The highlighted line is the one executing. Hover a ? for a pop question.
Input string
valid window
R
R
R
R
R
5
2
2
3
3
L
L
L
L
L
0
1
2
3
4
L leftR right pair window
left—
right—
adjacentEqualPairCount—
maxLength—
—
Current window
pairs
Longest substring—
0/28

Time Complexity

In the worst-case scenario, i.e., when all digits in s are the same, both left and right pointers traverse the string once.

Since the total number of pointer movements is bounded by 2n and all the remaining operations, including character comparisons, updating adjacentEqualPairCount, and updating maxLength, take constant time, the overall time complexity is O(2n) ~ O(n).

Space Complexity

We are maintaining only a few varaible to track the boundaries of the current substring, the number of adjacent equal pairs, and the length of the longest valid substring found so far.

Since no additional data structures are used and the number of variables remains constant regardless of the input size, the overall space complexity is O(1).


Follow-Up Questions

Q1. How would you modify this solution if the substring were allowed to contain at most k adjacent equal pairs instead of just one?

In the existing solution, we have:

while (adjacentEqualPairCount > 1) {
    // Shrink the window
}

We simply replace 1 with k:

while (adjacentEqualPairCount > k) {
    // Shrink the window
}