FastPrepMaximum Equalized Substrings After One Adjacent Swap

Maximum Equalized Substrings After One Adjacent Swap

Visa logoVisa● MediumINTERNOA
Learn

Problem statement

You are given a string s containing only L and R.

A substring is equalized when it contains the same number of L and R characters. You may swap at most one pair of adjacent characters in s.

After the optional swap, split the entire string into consecutive, nonempty equalized substrings. Return the maximum possible number of substrings in such a split. If the complete string has different total counts of L and R, return 0 because no complete equalized split is possible.

Function

maxEqualizedSubstrings(s: String) → int

Examples

Example 1

s = "RLRRLLRLRL"return = 5

Swap the adjacent R and L at indices 3 and 4. The string becomes RLRLRLRLRL, which splits as RL | RL | RL | RL | RL.

Example 2

s = "RL"return = 1

The whole string is already one equalized substring, and no adjacent swap can create a second nonempty part.

Example 3

s = "RRLL"return = 2

Swap the middle R and L to obtain RLRL, then split it as RL | RL.

Constraints

  • 1 <= s.length <= 2 * 10^5
  • Every character of s is either L or R.
  • You may perform zero or one adjacent swap.

More Visa problems

See Visa hiring insights
public int maxEqualizedSubstrings(String s) {
  // write your code here
}
s"RLRRLLRLRL"
expected5
Checking account…