Time Needed to Rearrange a Binary String — LeetCode 2380 Python Solution

MediumStringDynamic ProgrammingSimulation
Problem
#2380
Reading time
2 min

The problem

You are given a binary string s. In one second, all occurrences of "01" are simultaneously replaced with "10".

Example

Input
s = "0110101"
Output
4
Explanation
After one second, s becomes "1011010".

Python solution

Python
class Solution:
    def secondsToRemoveOccurrences(self, s: str) -> int:
        ans = 0
        while s.count('01'):
            s = s.replace('01', '10')
            ans += 1
        return ans

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2380. Time Needed to Rearrange a Binary String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2380. Time Needed to Rearrange a Binary String?
LeetCode 2380. Time Needed to Rearrange a Binary String is rated Medium on LeetCode.
What topics does LeetCode 2380. Time Needed to Rearrange a Binary String cover?
LeetCode 2380. Time Needed to Rearrange a Binary String is tagged String, Dynamic Programming and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview