Time Needed to Rearrange a Binary String — LeetCode 2380 Python Solution
MediumStringDynamic ProgrammingSimulation
- Problem
- #2380
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(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.