MediumNo. 2380
Time Needed to Rearrange a Binary String — LeetCode 2380 Python Solution
- Pattern
- Dynamic Programming
- Topics
- String, Dynamic Programming, Simulation
- 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
class Solution:
def secondsToRemoveOccurrences(self, s: str) -> int:
ans = 0
while s.count('01'):
s = s.replace('01', '10')
ans += 1
return ansComplexity
- 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
| No. | Problem | Difficulty |
|---|---|---|
| 0010 | Regular Expression Matching | Hard |
| 0022 | Generate Parentheses | Medium |
| 0032 | Longest Valid Parentheses | Hard |
| 0044 | Wildcard Matching | Hard |
| 0072 | Edit Distance | Medium |
| 0087 | Scramble String | Hard |
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.