Minimum Moves to Sort Binary Array (Amazon OA)
Given an array of binary digits, 0 and 1, sort the array so that all zeros are at one end and all ones are at the other. Which end does not matter. To sort the array, swap any two adjacent elements. Determine the minimum number of swaps to sort the array.
Worked Examples
arr = [0, 1, 0, 1]1arr = [1, 1, 1, 1, 0, 0, 0, 0]0arr = [1, 1, 1, 1, 0, 1, 0, 1]3⚖️Formal Constraints & Bounds
1 <= n <= 105arr[i]is in the set{0, 1}
Why It Works & Core Invariant
Adjacent swaps change inversion count by unit distance: bubbling an element from reader to writer takes exactly reader - writer moves.
Real-World Scenario & Production Applications
Sorting network packet buffers, minimal-energy bit-shuffling in memory controllers, and quantum gate scheduling where adjacent exchanges have unit cost.
Subproblems & Recurrence Decomposition3 Phases
Skip initial zeros already in place at index 0. For each subsequent 0 discovered at reader, accumulate reader - writer adjacent swaps and advance writer by 1.
zero_left = 0
w = 0
while w < len(arr) and arr[w] == 0: w += 1
for r in range(w, len(arr)):
if arr[r] == 0:
zero_left += r - w
w += 1Step-by-Step Execution Trace Table
| Pass | Reader | arr[reader] | Condition / Action | Writer | Delta (reader - writer) | Cumulative Moves |
|---|---|---|---|---|---|---|
| 0s Left | 4 | 0 | Match! Bubble to writer=0 | 1 | 4 | |
| 0s Left | 6 | 0 | Match! Bubble to writer=1 | 2 | 9 (Total 0s) | |
| 1s Left | 5 | 1 | Match! Bubble to writer=4 | 5 | 1 | |
| 1s Left | 7 | 1 | Match! Bubble to writer=5 | 6 | 3 (Total 1s) | |
| Final | — | — | Return | — | — | 3 |
| 1 | zero_left = ones_left = 0 |
| 2 | w0 = 0; while w0 < n and arr[w0] == 0: w0 += 1 |
| 3 | for r in range(w0, n): if arr[r] == 0: zero_left += r - w0; w0 += 1 |
| 4 | w1 = 0; while w1 < n and arr[w1] == 1: w1 += 1 |
| 5 | for r in range(w1, n): if arr[r] == 1: ones_left += r - w1; w1 += 1 |
| 6 | return min(zero_left, ones_left) |
Target: Minimum Moves to Sort Binary Array (Amazon OA). Elements already in their final position require 0 moves; advance destination frontier.
Indices step monotonically inward or rightward. Each step permanently eliminates an entire row, column, or infeasible candidate window.
while (left < right) for converging pointers; while (right < n) with inner window shrink.
Conceptual Narrative
🧭 Conceptual Foundation & Pattern Intuition
Sorting a binary array using only adjacent swaps is equivalent to counting the number of inversions required to separate the 0s and 1s. While general inversion counting on arbitrary sequences requires with a Fenwick tree or Merge Sort, binary elements afford an elegant two-pointer reader-writer technique.
🏟️ The Analogy: The Conveyor Belt Sorter
Picture an inspection belt where items of two categories pass by. You have a target collection dock on the far left. The writer pointer marks the next open slot at the dock. The reader pointer walks down the belt. When it discovers a target item, passing it hand-to-hand back to the dock takes exactly reader - writer adjacent swaps. As the item docks, writer advances by 1.
🪄 The Mathematical Harmony / Magic Trick
for reader in range(writer, len(arr)): if arr[reader] == target: moves += reader - writer writer += 1 Because every adjacent swap exchanges two neighboring items, shifting an item leftwards by 1 position decrements its distance to writer by 1 and shifts every intervening item rightwards by 1 position. The relative order of the intervening items is preserved without increasing their future distances!
💡 Summary
By running two linear reader-writer compaction passes—one assuming all 0s move to the left, and one assuming all 1s move to the left—we evaluate both valid sorted states in operations, returning in time and space.
Assuming 0s must always go to the left: The problem specifies 'Which end does not matter.' Sorting to [1, 1, ..., 0, 0] may require fewer adjacent swaps than [0, 0, ..., 1, 1]. Always compute both directions and take the minimum.
Resetting writer to 0 instead of maintaining frontier: The writer index marks where the next matching element must land. Each time a target element is shifted, incrementing
writer += 1is mandatory to avoid computing swaps to already-occupied slots.Overcomplicating with Fenwick tree or Merge Sort: Inversion count algorithms for arbitrary values take time and space. Because all values are binary {0, 1}, two-pointer reader-writer simulation solves this in time and space.
4-Phase Thought Process Model
You will see how a senior engineer computes minimum adjacent swaps using reader-writer pointer distances instead of heavy inversion algorithms.
Pattern Recognition Signals
The 10-second spot
Binary digits {0, 1} + adjacent swaps only + move all 0s to one end and 1s to other end.
Formulating the Predicate & Invariants
Turning intuition into a boolean rule
Invariant: arr[0..writer-1] holds compacted target prefix. Next target at reader requires exactly reader - writer adjacent swaps to reach writer.
Silent Failure Traps & Edge Cases
Where confident candidates still lose points
Assuming 0s must always move left: the prompt states 'which end does not matter', requiring evaluation of both zeros-left and ones-left configurations.
Over-engineering with Fenwick trees or Merge Sort: arbitrary inversion counting is
O(N log N), but binary arrays permit an exactO(N)two-pointer simulation.Forgetting to skip leading elements already settled at the destination frontier before beginning reader scan.
The 60-Second Interview Pitch
Say this out loud before you type a single line
"Because only adjacent swaps are allowed, moving a target digit from index reader to index writer across intervening digits takes exactly reader - writer moves. I run two linear passes: one computing swaps to bring all 0s to the left, and one computing swaps to bring all 1s to the left. Returning min(zeros_left, ones_left) runs in
O(N)time andO(1)space."
So: test both polarities (zeros left vs ones left) using reader - writer compaction distance in 2N steps and return the minimum.
Complexity & Mathematical Proof
O(N)
Look at the execution steps: The array of length N is traversed twice (once for zeros-left, once for ones-left). Each pass visits each index at most once with O(1) arithmetic. Total time is 2N = O(N).
O(1) Auxiliary
Look at memory allocations: Only integer pointer variables (writer, reader, zero_left_counter, ones_left_counter) are maintained. No auxiliary arrays or recursive stacks are allocated.
Look at the execution steps: The array of length N is traversed twice (once for zeros-left, once for ones-left). Each pass visits each index at most once with O(1) arithmetic. Total time is 2N = O(N).
Derivation Progression
Scans array accumulating reader - writer for all 0s.
Scans array accumulating reader - writer for all 1s.
Strictly linear time with zero dynamic allocation.
Variable Definitions
Memory Architecture & Bounds
O(1) Iterative
O(1) No heap allocation
O(1) Scalar integer return
Boundary Best / Worst Cases
$O(N)$
$O(N)$
$O(N)$
Pointer Invariant Transition Progression
Senior SWE Deconstruction & Hardware Caveats
Triggers: **"binary digits 0 and 1"**, **"swap any two adjacent elements"**, **"all zeros at one end and all ones at the other"**, **"minimum number of swaps"**. The restriction to adjacent swaps means each move changes the inversion count by exactly 1. Moving a target element from index reader to index writer across adjacent elements requires exactly reader - writer swaps.
, . Requires strictly time and auxiliary space.
Skipping dual-polarity check: the prompt states 'which end does not matter', so evaluating both zeros-to-left and ones-to-left is required to obtain the true minimum.
Core Algorithmic State Invariants
Because each adjacent swap exchanges neighboring indices, moving an element from reader to writer takes exactly reader - writer moves. The reader-writer distance computes the exact inversion count in O(1) time per element without requiring physical array manipulation.
The writer pointer w tracks the next available destination slot for the target digit. Skipping initial target digits settled at the start requires 0 moves. As each subsequent target digit is discovered, advancing writer by 1 preserves relative ordering of compacted elements.
Because grouping all zeros on either the left or right side is permissible, evaluating both zeros-to-left and ones-to-left configurations in two sequential linear passes guarantees optimality in O(N) time and O(1) auxiliary space.
Minimum Moves to Sort Binary Array (Amazon OA)
Given an array of binary digits, 0 and 1, sort the array so that all zeros are at one end and all ones are at the other. Which end does not matter. To sort the array, swap any two adjacent elements. Determine the minimum number of swaps to sort the array.
Worked Examples
arr = [0, 1, 0, 1]1arr = [1, 1, 1, 1, 0, 0, 0, 0]0arr = [1, 1, 1, 1, 0, 1, 0, 1]3⚖️Formal Constraints & Bounds
1 <= n <= 105arr[i]is in the set{0, 1}
Why It Works & Core Invariant
Adjacent swaps change inversion count by unit distance: bubbling an element from reader to writer takes exactly reader - writer moves.
Real-World Scenario & Production Applications
Sorting network packet buffers, minimal-energy bit-shuffling in memory controllers, and quantum gate scheduling where adjacent exchanges have unit cost.
Subproblems & Recurrence Decomposition3 Phases
Skip initial zeros already in place at index 0. For each subsequent 0 discovered at reader, accumulate reader - writer adjacent swaps and advance writer by 1.
zero_left = 0
w = 0
while w < len(arr) and arr[w] == 0: w += 1
for r in range(w, len(arr)):
if arr[r] == 0:
zero_left += r - w
w += 1Step-by-Step Execution Trace Table
| Pass | Reader | arr[reader] | Condition / Action | Writer | Delta (reader - writer) | Cumulative Moves |
|---|---|---|---|---|---|---|
| 0s Left | 4 | 0 | Match! Bubble to writer=0 | 1 | 4 | |
| 0s Left | 6 | 0 | Match! Bubble to writer=1 | 2 | 9 (Total 0s) | |
| 1s Left | 5 | 1 | Match! Bubble to writer=4 | 5 | 1 | |
| 1s Left | 7 | 1 | Match! Bubble to writer=5 | 6 | 3 (Total 1s) | |
| Final | — | — | Return | — | — | 3 |
| 1 | zero_left = ones_left = 0 |
| 2 | w0 = 0; while w0 < n and arr[w0] == 0: w0 += 1 |
| 3 | for r in range(w0, n): if arr[r] == 0: zero_left += r - w0; w0 += 1 |
| 4 | w1 = 0; while w1 < n and arr[w1] == 1: w1 += 1 |
| 5 | for r in range(w1, n): if arr[r] == 1: ones_left += r - w1; w1 += 1 |
| 6 | return min(zero_left, ones_left) |
Target: Minimum Moves to Sort Binary Array (Amazon OA). Elements already in their final position require 0 moves; advance destination frontier.
Indices step monotonically inward or rightward. Each step permanently eliminates an entire row, column, or infeasible candidate window.
while (left < right) for converging pointers; while (right < n) with inner window shrink.
Conceptual Narrative
🧭 Conceptual Foundation & Pattern Intuition
Sorting a binary array using only adjacent swaps is equivalent to counting the number of inversions required to separate the 0s and 1s. While general inversion counting on arbitrary sequences requires with a Fenwick tree or Merge Sort, binary elements afford an elegant two-pointer reader-writer technique.
🏟️ The Analogy: The Conveyor Belt Sorter
Picture an inspection belt where items of two categories pass by. You have a target collection dock on the far left. The writer pointer marks the next open slot at the dock. The reader pointer walks down the belt. When it discovers a target item, passing it hand-to-hand back to the dock takes exactly reader - writer adjacent swaps. As the item docks, writer advances by 1.
🪄 The Mathematical Harmony / Magic Trick
for reader in range(writer, len(arr)): if arr[reader] == target: moves += reader - writer writer += 1 Because every adjacent swap exchanges two neighboring items, shifting an item leftwards by 1 position decrements its distance to writer by 1 and shifts every intervening item rightwards by 1 position. The relative order of the intervening items is preserved without increasing their future distances!
💡 Summary
By running two linear reader-writer compaction passes—one assuming all 0s move to the left, and one assuming all 1s move to the left—we evaluate both valid sorted states in operations, returning in time and space.
Assuming 0s must always go to the left: The problem specifies 'Which end does not matter.' Sorting to [1, 1, ..., 0, 0] may require fewer adjacent swaps than [0, 0, ..., 1, 1]. Always compute both directions and take the minimum.
Resetting writer to 0 instead of maintaining frontier: The writer index marks where the next matching element must land. Each time a target element is shifted, incrementing
writer += 1is mandatory to avoid computing swaps to already-occupied slots.Overcomplicating with Fenwick tree or Merge Sort: Inversion count algorithms for arbitrary values take time and space. Because all values are binary {0, 1}, two-pointer reader-writer simulation solves this in time and space.
4-Phase Thought Process Model
You will see how a senior engineer computes minimum adjacent swaps using reader-writer pointer distances instead of heavy inversion algorithms.
Pattern Recognition Signals
The 10-second spot
Binary digits {0, 1} + adjacent swaps only + move all 0s to one end and 1s to other end.
Formulating the Predicate & Invariants
Turning intuition into a boolean rule
Invariant: arr[0..writer-1] holds compacted target prefix. Next target at reader requires exactly reader - writer adjacent swaps to reach writer.
Silent Failure Traps & Edge Cases
Where confident candidates still lose points
Assuming 0s must always move left: the prompt states 'which end does not matter', requiring evaluation of both zeros-left and ones-left configurations.
Over-engineering with Fenwick trees or Merge Sort: arbitrary inversion counting is
O(N log N), but binary arrays permit an exactO(N)two-pointer simulation.Forgetting to skip leading elements already settled at the destination frontier before beginning reader scan.
The 60-Second Interview Pitch
Say this out loud before you type a single line
"Because only adjacent swaps are allowed, moving a target digit from index reader to index writer across intervening digits takes exactly reader - writer moves. I run two linear passes: one computing swaps to bring all 0s to the left, and one computing swaps to bring all 1s to the left. Returning min(zeros_left, ones_left) runs in
O(N)time andO(1)space."
So: test both polarities (zeros left vs ones left) using reader - writer compaction distance in 2N steps and return the minimum.
Complexity & Mathematical Proof
O(N)
Look at the execution steps: The array of length N is traversed twice (once for zeros-left, once for ones-left). Each pass visits each index at most once with O(1) arithmetic. Total time is 2N = O(N).
O(1) Auxiliary
Look at memory allocations: Only integer pointer variables (writer, reader, zero_left_counter, ones_left_counter) are maintained. No auxiliary arrays or recursive stacks are allocated.
Look at the execution steps: The array of length N is traversed twice (once for zeros-left, once for ones-left). Each pass visits each index at most once with O(1) arithmetic. Total time is 2N = O(N).
Derivation Progression
Scans array accumulating reader - writer for all 0s.
Scans array accumulating reader - writer for all 1s.
Strictly linear time with zero dynamic allocation.
Variable Definitions
Memory Architecture & Bounds
O(1) Iterative
O(1) No heap allocation
O(1) Scalar integer return
Boundary Best / Worst Cases
$O(N)$
$O(N)$
$O(N)$
Pointer Invariant Transition Progression
Senior SWE Deconstruction & Hardware Caveats
Triggers: **"binary digits 0 and 1"**, **"swap any two adjacent elements"**, **"all zeros at one end and all ones at the other"**, **"minimum number of swaps"**. The restriction to adjacent swaps means each move changes the inversion count by exactly 1. Moving a target element from index reader to index writer across adjacent elements requires exactly reader - writer swaps.
, . Requires strictly time and auxiliary space.
Skipping dual-polarity check: the prompt states 'which end does not matter', so evaluating both zeros-to-left and ones-to-left is required to obtain the true minimum.
Core Algorithmic State Invariants
Because each adjacent swap exchanges neighboring indices, moving an element from reader to writer takes exactly reader - writer moves. The reader-writer distance computes the exact inversion count in O(1) time per element without requiring physical array manipulation.
The writer pointer w tracks the next available destination slot for the target digit. Skipping initial target digits settled at the start requires 0 moves. As each subsequent target digit is discovered, advancing writer by 1 preserves relative ordering of compacted elements.
Because grouping all zeros on either the left or right side is permissible, evaluating both zeros-to-left and ones-to-left configurations in two sequential linear passes guarantees optimality in O(N) time and O(1) auxiliary space.
| Canonical Invariant | Concrete Code | Engineering Rationale |
|---|---|---|
| Skip leading target elements already settled at frontier | while writer0 < n and arr[writer0] == 0:
writer0 += 1 | Elements already in their final position require 0 moves; advance destination frontier. |
| Sequential reader scan over unsorted trailing stretch | for reader0 in range(writer0, n): | Reader traverses rightward to discover matching candidate digits. |
| Inversion delta accumulator for matching target elements | if arr[reader0] == 0:
zero_moves += reader0 - writer0
writer0 += 1 | Bubbling arr[reader0] across intervening elements to writer slot takes exactly (reader0 - writer0) adjacent swaps. |
| Bilateral polarity evaluation (0s left vs 1s left) | return min(zero_moves, ones_moves) | The orientation requirement permits either end; return the minimal move configuration. |