#2380
Time Needed to Rearrange a Binary String
MediumStringDynamic ProgrammingSimulationTwo PointersSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach leverages the observation that the number of seconds needed is determined by the maximum distance between the leftmost '0' and the rightmost '1' in the string. This allows us to calculate the result in linear time.
⚙️
Algorithm
3 steps- 1Step 1: Initialize variables to track the positions of the leftmost '0' and rightmost '1'.
- 2Step 2: Traverse the string to find these positions.
- 3Step 3: The number of seconds needed is the maximum of the distances between these positions.
solution.py6 lines
1def seconds_to_rearrange_optimal(s):
2 leftmost_zero = s.find('0')
3 rightmost_one = s.rfind('1')
4 if leftmost_zero == -1 or rightmost_one == -1 or leftmost_zero > rightmost_one:
5 return 0
6 return rightmost_one - leftmost_zeroℹ
Complexity note: This complexity is linear because we only traverse the string twice — once to find the leftmost '0' and once to find the rightmost '1'.
- 1The number of seconds is determined by the distance between the leftmost '0' and the rightmost '1'.
- 2If there are no '0's or '1's, or if '0's are to the right of '1's, the result is 0.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.