MediumNo. 2380

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

Topics
String, Dynamic Programming, Simulation
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

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

Complexity

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

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

Related problems
No.ProblemDifficulty
0010Regular Expression MatchingHard
0022Generate ParenthesesMedium
0032Longest Valid ParenthesesHard
0044Wildcard MatchingHard
0072Edit DistanceMedium
0087Scramble StringHard

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.

Free to download. Check it runs on your machine, then pick a plan.