easyStringsPattern: Two Pointers

Max Alternating Substring Length Solution

Problem Statement

You are given a string consisting of 'G' and 'R' characters. Find the maximum length of a substring that has alternating 'G' and 'R' characters.

Examples

Example 1:
Input:RG
Output:0
Explanation: The substring 'RG' has alternating 'G' and 'R' characters and its length is 2.
Example 2:
Input:GGRR
Output:0
Explanation: The substring 'GRGR' has alternating 'G' and 'R' characters and its length is not explicitly present but 'GGRR' as a whole doesn't, however 'G' and 'R' can be considered for this.
Example 3:
Input:RRGG
Output:0
Explanation: The substring 'RGRG' has alternating 'G' and 'R' characters and its length is not explicitly present but 'RRGG' as a whole doesn't, however 'R' and 'G' can be considered for this.

Constraints

  • The input string consists only of 'G' and 'R' characters.
  • The input string may be empty.
  • The maximum length of the input string is 10000.
Time: O(n) Space: O(1)
You can solve this problem in O(n) time complexity by using a state machine or dynamic programming.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

def max_alternating_substring_length(s): n = len(s) res = 0 i = 0 while i < n: j = i while j < n and (s[j] == 'G' and s[j-1] == 'G' or s[j] == 'R' and s[j-1] == 'R'): j += 1 res = max(res, j - i) i = j + 1 return res;