#2938

Separate Black and White Balls

Medium
Two PointersStringGreedyTwo PointersGreedy Algorithms
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)

Instead of swapping, we can count how many '0's each '1' has to jump over to reach its final position. This allows us to calculate the minimum swaps needed in a single pass.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a counter for the number of '0's encountered as we traverse the string.
  2. 2Step 2: For each '1' encountered, add the current count of '0's to the total steps.
  3. 3Step 3: Continue until the end of the string.
solution.py11 lines
1def minSwaps(s):
2    count_zeros = 0
3    steps = 0
4    for char in s:
5        if char == '0':
6            count_zeros += 1
7        else:
8            steps += count_zeros
9    return steps
10
11print(minSwaps('101'))

Complexity note: This approach is linear because we only make a single pass through the string, counting '0's and calculating steps simultaneously.

  • 1Swapping adjacent elements can be inefficient; counting jumps is often faster.
  • 2Understanding the problem allows you to identify patterns, like counting instead of swapping.

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