Split A String Into Balanced Strings in Javascript

Christa Gammage
2 min readOct 13, 2020

If you’re studying for your coding interviews, you may come across this “easy” coding challenge. “Balanced” strings are those who have equal quantity of ‘L’ and ‘R’ characters. Given a balanced string s split it in the maximum amount of balanced strings. Return the maximum amount of splitted balanced strings. An example input may look like “RLRRLLRLRL” and the function should return “4.” This is because “RLRRLLRLRL” can be split into “RL”, “RRLL”, “RL”, “RL”, each substring contains same number of ‘L’ and ‘R’.

We know that we want to return the number of splits we can do, rather than the actual splits themselves. So let’s set up a counter variable to hold our split number.

Next, we’ll loop through our string. For each “L,” we’ll increase the counter, and for each “R,” we’ll decrease it. That way, if there are an equal number of “L”s and “R”s, the counter should be at 0 by the time it finishes looping through the string.

At this point, if the counter is at 0 after the “if” statement, we know that that’s an even split of the string. In which case, our split string count should be increased by one. Let’s create an “answer” variable that will hold the actual number we will be returning at the end of our function. We’ll have it check if the “counter” variable is at 0, in which case we’d increase our “answer” variable by one.

Lastly, we’ll want to return our “answer” count.

As this function’s run speed depends on the length of s, it it’s time complexity would be O(N).

--

--