15% off all plans & roadmaps Use code

See plans

Separate Black and White Balls

Updated

TL;DR: Every black ball must cross each white ball that sits to its right, so the answer is the number of those black-before-white pairs. One left-to-right pass with a second pointer for the next white slot adds them up in O(n) time and O(1) space.

Problem

There are n balls on a table. Each ball is either black or white.

You get a 0-indexed binary string s of length n. The character 1 means a black ball and 0 means a white ball.

In each step, you may pick two adjacent balls and swap them.

Return the minimum number of steps needed to group all black balls on the right and all white balls on the left.

Example 1

Input: s = '101'
Output: 1
Explanation: Swap s[0] and s[1] to get '011'. The black balls are now grouped on the right, so one step is enough.

Example 2

Input: s = '100'
Output: 2
Explanation: Swap s[0] and s[1] to get '010'. Then swap s[1] and s[2] to get '001'. Fewer than 2 steps cannot work.

Example 3

Input: s = '0111'
Output: 0
Explanation: The black balls are already on the right, so no step is needed.

Constraints

  • 1 <= n == s.length <= 10^5
  • s[i] is either '0' or '1'.

Constraints that matter

  • n up to 10^5 rules out simulating the swaps. The answer can reach about 2.5 * 10^9 swaps, and a simulation would perform every one of them.
  • The answer can exceed 2^31 - 1, so the running total needs a 64-bit type in Java, C++ and C#.
  • Only the characters '0' and '1' appear, so one scan that tracks two counters covers every input.
  • With n up to 10^5, an O(n) scan fits the limit easily, while anything near O(n^2) work does not.

View on LeetCode

Hints

Hint 1

The swaps are not the real problem.

Hint 2

The naive solution treats the input as an array that needs sorting.

Solution

Intuition

The swaps are not the real problem. The problem is counting the pairs of balls that are in the wrong order, because each adjacent swap fixes exactly one such pair. A black ball on the left of a white ball has to cross it at least once, and each crossing costs one swap. So the answer is the number of pairs where a black ball sits to the left of a white ball.

Picture a queue where each white ball is a person who must step past every black ball ahead of them. The black balls are the people being passed, and each step past one is one swap.

The pattern here is two pointers. One pointer reads the string from left to right. The second pointer, called slot, marks where the next white ball belongs on the left edge. A white ball at index i with slot value k has k white balls before it, so the other i - k characters before it are black, and each of those must cross it.

What points you to this pattern: the target layout is fixed (white on the left, black on the right), every move is between adjacent balls, and each ball's cost is the distance it must travel. When the target is known and the moves are adjacent, a single sweep with a write position usually gives the answer. If you catch yourself writing a bubble sort, stop and count the crossings instead.

Watch the pattern animation

Worked example

Input: s = '1100101'
Output: 7
Explanation: The white balls sit at indices 2, 3 and 5. The white ball at index 2 has 2 black balls on its left, and so does the white ball at index 3. The white ball at index 5 has 3 black balls on its left, at indices 0, 1 and 4. Each of those black balls must cross its white ball once, so the total is 2 + 2 + 3 = 7.

Approach 1: Brute force: repeated adjacent swaps

The naive solution treats the input as an array that needs sorting. It scans the string, swaps every adjacent '10' it finds into '01', and counts each swap. It repeats full scans until one scan makes no swap. Each swap removes exactly one black-before-white pair, so the total is correct, but every scan walks the whole string again.

The loop stops only when a full scan finds no '10' pair. On a string with 5 * 10^4 black balls followed by 5 * 10^4 white balls, the answer is 2.5 * 10^9, so the simulation performs that many swaps. Each swap also needs a scan to find it, which makes the work far too large for the limit.

Steps

  1. Convert s into a mutable array of characters, because Python strings cannot change in place.
  2. Scan i from 0 to n - 2 and compare chars[i] with chars[i + 1].
  3. When you see a '1' followed by a '0', swap them and add 1 to steps.
  4. After the scan, repeat it if that scan made at least one swap.
  5. When a full scan makes no swap, return steps.

Dry run

Start from the example '1100101'. Pass 1 swaps at indices 1, 2 and 4, giving '1001011' after 3 swaps. Pass 2 swaps at indices 0, 1 and 3, giving '0010111' after 6 swaps. Pass 3 swaps at index 2, giving '0001111' after 7 swaps, and pass 4 finds no '10' pair, so the function returns 7.

Complexity

TimeO(n^2)
SpaceO(n)

Let n be the length of s. One scan checks n - 1 adjacent pairs, so it costs O(n). A bubble-style sweep needs at most about n scans before a clean one, so the total work is O(n) times O(n), which is O(n^2). The mutable copy takes O(n) space, and the counter takes O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def minimumSteps(self, s: str) -> int:
        chars = list(s)  # strings are immutable, so work on a list
        n = len(chars)
        steps = 0
        changed = True
        while changed:
            changed = False
            for i in range(n - 1):
                if chars[i] == '1' and chars[i + 1] == '0':
                    chars[i], chars[i + 1] = chars[i + 1], chars[i]
                    steps += 1
                    changed = True
        return steps

The In-place Array Modification infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

In-place Array Modification

Part of Two Pointers

Approach 2: Two pointers, one passOptimalIn-place Array Modification

What's slow: the brute force never asks where each white ball ends up. It finds swaps one at a time and rescans the string to find the next one. The insight that fixes it is that the final layout is fixed. Each white ball has a known target, which is the leftmost free slot, and its cost is the distance it must travel to reach that slot.

That distance equals the number of black balls the white ball must pass. A black ball adds no cost by itself. It is counted when a white ball to its right is processed. So you can add the costs during one left-to-right scan, with slot tracking the next target.

Why no sequence of swaps can do better: each adjacent swap changes the number of black-before-white pairs by exactly one, and the sorted string has zero such pairs. So at least that many swaps are needed. The sum above equals that pair count, so it is the minimum.

Steps

  1. Set total to 0 and slot to 0. Slot is the next index a white ball should occupy.
  2. Read i from 0 to n - 1.
  3. If s[i] is '1', skip it. It only adds to the cost of white balls that come after it.
  4. If s[i] is '0', add i - slot to total.
  5. Add 1 to slot, because one more white ball is now in place.
  6. Return total after the scan.

Dry run

Start with total = 0 and slot = 0. Read the table from top to bottom.

is[i]actionslot aftertotal after
01skip00
11skip00
20add 2 - 0 = 212
30add 3 - 1 = 224
41skip24
50add 5 - 2 = 337
61skip37

The white ball at index 2 passes the blacks at indices 0 and 1. The white ball at index 3 passes the same two blacks. The white ball at index 5 passes three blacks, at indices 0, 1 and 4. The final total is 7, which matches the expected output.

Complexity

TimeO(n)
SpaceO(1)

Let n be the length of s. The loop runs once for each character, and each iteration does a constant amount of work, so the time is O(n). The solution keeps only total, slot and the loop index, which are three numbers regardless of n, so the extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def minimumSteps(self, s: str) -> int:
        total = 0  # swaps counted so far
        slot = 0   # next index a white ball should occupy
        for i, ch in enumerate(s):
            if ch == '0':
                total += i - slot  # blacks to the left of this white ball
                slot += 1
        return total

Common mistakes

  • total += i instead of total += i - slot. The raw index also counts the white balls already placed on the left, which are not crossings. Subtract slot to count only the black balls.
  • total declared as a 32-bit int, for example int total = 0 in Java, C++ or C#. For n = 10^5 the answer can reach about 2.5 * 10^9, which wraps to a negative value. Use long, long long or int64 for the accumulator, and match the return type your judge declares.
  • if ch == '1': total += zeros_seen. This counts pairs with a white ball on the left, which is the reverse of what the answer needs. Add on each white ball the number of black balls seen so far, which equals i - slot.
  • slot += 1 placed inside the '1' branch. Only white balls take a slot. Advancing slot on black balls pushes the target too far right, so later white balls look cheaper than they are.
  • s[i], s[i + 1] = s[i + 1], s[i] on a Python string. Python strings are immutable, so this raises a TypeError. Convert the string to a list first, as the brute force above does.

Edge cases

  • '0' or '0000': no black ball sits left of a white ball, so the answer is 0.
  • '1' or '1111': every ball is black and already on the right, so the answer is 0.
  • '10': one black ball must cross one white ball, so the answer is 1.
  • '101010': the white balls sit at indices 1, 3 and 5 with 1, 2 and 3 blacks on their left, so the answer is 6.
  • '0' * 50000 + '1' * 50000: the layout is already grouped, so the answer is 0. The reverse, '1' * 50000 + '0' * 50000, is the worst case with an answer of 2.5 * 10^9, which needs a 64-bit total.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Separate Black and White Balls, with how to answer them.

Unlock the follow-ups

Separate Black and White Balls FAQ

What is the time complexity of Separate Black and White Balls?

The optimal solution runs in O(n) time, where n is the length of s, because it reads each character once. The brute force repeats full scans and runs in O(n^2) time in the worst case. The complexity section above gives the counting argument for both.

Why use two pointers for Separate Black and White Balls?

One pointer reads the string, and the other tracks the next free slot on the left. This is the same layout used in in-place array edits. The gap between the two pointers gives the number of swaps for each white ball, so one pass computes the total.

Can Separate Black and White Balls be solved in O(1) extra space?

Yes. The solution keeps two integers and a total, which is O(1) extra space. It does not modify the input or build an array.

Why does the answer need a 64-bit integer?

A string of length 10^5 can hold 5 * 10^4 black balls followed by 5 * 10^4 white balls. That layout needs 2.5 * 10^9 swaps, which is above the 32-bit signed limit of about 2.1 * 10^9. A 64-bit total avoids the overflow.

How do I count the swaps without actually swapping?

Each white ball's cost equals the number of black balls before it, which is its index minus the number of white balls already placed. Add that value for each white ball during the scan. The string itself never changes.

Asked at

See which companies ask this — Pro

Practise it