#3228

Maximum Number of Operations to Move Ones to the End

Medium
StringGreedyCountingGreedyCounting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach counts the number of '1's and '0's, then calculates how many operations can be performed based on their positions. This method is efficient and runs in linear time.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a counter for '1's and a counter for operations.
  2. 2Step 2: Traverse the string and for each '1' found, add the number of '0's that have been seen so far to the operations counter.
  3. 3Step 3: Return the operations counter as the result.
solution.py10 lines
1# Full working Python code
2s = '1001101'
3count_ones = 0
4operations = 0
5for char in s:
6    if char == '1':
7        operations += count_ones
8    else:
9        count_ones += 1
10print(operations)

Complexity note: The time complexity is O(n) because we only traverse the string once, counting '1's and calculating operations in a single pass. The space complexity is O(1) since we use a fixed amount of extra space.

  • 1Performing operations on the leftmost '1' is optimal as it maximizes the number of moves.
  • 2Counting the number of '0's encountered allows us to calculate potential moves efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.