Hi👋SpeedAlgo • Deliberate Practice & Cognitive Ergonomics for Software Engineers

An interactive algorithm mastery and technical interview preparation platform published by Hi👋WebEnterprise. Built for senior and staff software engineers preparing for rigorous coding screens at top tech companies (FAANG/MAMAA).

13 Core Algorithmic Patterns & 225 Practice Problems

  • 1. Two Pointers (16 Paradigms, 43 Problems): Opposite ends, sorted pair sums, palindrome verification, trapping rain water, 3Sum, container with most water — includes the Sliding Window and Fast & Slow Pointers paradigms (contiguous subarray invariants, longest substrings, Floyd's cycle detection, linked list middle).
  • 2. Binary Search (9 Paradigms, 14 Problems): Monotonic predicate partitioning (feasible(x)), boundary search, rotated sorted arrays, square roots, minimum ship capacity, median of two sorted arrays, matrix median on value range.
  • 3. Bit Manipulation (5 Paradigms, 11 Problems): Counting set bits, XOR cancellation, bit reversal, bitmask pairing, maximum XOR with a bitwise trie.
  • 4. Math & Geometry (8 Paradigms, 14 Problems): Sieve of Eratosthenes, integer/roman conversions, modular arithmetic, geometric simulation.
  • 5. Tree/Graph Depth-First Search (15 Paradigms, 24 Problems): Path sums, lowest common ancestor, tree diameter, validating BSTs, tree DP (House Robber III, Binary Tree Cameras).
  • 6. Tree/Graph Breadth-First Search (5 Paradigms, 12 Problems): Level-order traversals, shortest path in unweighted graphs, zig-zag traversals, rotting oranges, word ladders.
  • 7. Graphs (12 Paradigms, 22 Problems): Topological sort, cycle detection, Dijkstra's algorithm, bipartite graph validation, network delay.
  • 8. Backtracking (6 Paradigms, 14 Problems): Subsets, permutations, combinations, constraint satisfaction, pruning, N-Queens, Sudoku solver.
  • 9. Dynamic Programming (13 Paradigms, 28 Problems): Memoization vs tabulation, 0/1 knapsack, unbounded knapsack, coin change, edit distance, longest common subsequence.
  • 10. Heap / Priority Queue (9 Paradigms, 11 Problems): Running medians, top-k elements, interval scheduling, IPO, k-way merges.
  • 11. Advanced Data Structures (7 Paradigms, 17 Problems): Trie (prefix tree), Union-Find (Disjoint Set Union), LRU Cache, LFU Cache, range-sum queries with updates.
  • 12. Stack (5 Paradigms, 9 Problems): Next greater element, largest rectangle in histogram, remove k digits, decode string, min stack.
  • 13. Intervals & Greedy (2 Paradigms, 6 Problems): Merge intervals, interval scheduling, meeting rooms by sweep line, jump game.

4-Stage Deliberate Practice Framework

  1. Stage 1 (Compare & Learn): Read the pattern's mental model, loop invariant and Big-O proof, compare the pattern's template with the problem's solution side by side, and use the step-by-step debugger. The solution can also be shown in C#, Java, TypeScript, C++, Go or Rust for almost every problem.
  2. Stage 2 (Active Recall): Rebuild the solution from memory in a code editor, with an invariant checklist and optional progressive hints, and check it against a judged test suite.
  3. Stage 3 (AI Interview Coach, coming soon): A mock-interview stage still in development; for now, students go straight from Stage 2 to Stage 4.
  4. Stage 4 (Solve on Your Own): Solve a new problem on your own against a 15-minute timer; your code is graded against a test suite. Python and TypeScript run in your browser and C# runs on our server (design problems grade in Python and TypeScript).

Equipped with a spaced-repetition review hub on a fixed 7-step schedule (1 day up to 90 days), a two-pane Studio workspace, and study notes.

Pricing, Access & Commercial Terms

  • Core Curriculum: 100% Free. No credit card required.
  • Coins: New accounts get 40 free coins once, the daily claim adds +20 coins once a day, and inviting a friend earns you +25 coins when they complete their first practice step. These are the only ways to earn coins.
  • AI Coach: Each AI coach question costs 1-5 coins, priced by the server according to its size.
  • BYOK (Bring Your Own Key): AI coaching is free with your own Google Gemini, OpenAI or OpenRouter API key (BYOK).
  • Extras: Coins also unlock extras for 24 hours: a Recall hint level (1 coin), a Solve solution reveal (2), a LeetCode problem card's solutions (1) and a pattern's extra canonical problems (1).
  • Payments & Refunds: Nothing on the site is sold for money: coins can only be earned, never bought. There are no subscriptions or charges, so there is nothing to refund.
  • Platform Operator: Hi👋WebEnterprise. Support & policies at hispeedalgo.com.
Skip to main content
Hi👋SpeedAlgo

Invariant-First Algorithmic Mastery

Arena
238Items
Theory Context•Two Pointers & Sliding Window
HardLC 2193

Minimum Moves to Sort Binary Array (Amazon OA)

Target Frequency:AmazonMicrosoft

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

Example 1
Input:arr = [0, 1, 0, 1]
Output:1
Explanation: With 1 move, switching elements 1 and 2, yields [0, 0, 1, 1], a sorted array.
Example 2
Input:arr = [1, 1, 1, 1, 0, 0, 0, 0]
Output:0
Explanation: The array is already sorted with all 1s on the left and all 0s on the right, so 0 moves are necessary.
Example 3
Input:arr = [1, 1, 1, 1, 0, 1, 0, 1]
Output:3
Explanation: Perform the minimal sequence of 3 moves to sort the array into [1, 1, 1, 1, 1, 1, 0, 0].

⚖️Formal Constraints & Bounds

  • 1 <= n <= 105

  • arr[i] is in the set {0, 1}

Deep-Dive & Conceptual Insights

Core Insight

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

🧩Subproblem 1: Zeros-to-Left Compaction Scan

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.

Mathematical Recurrence / Code Invariant
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 += 1

Step-by-Step Execution Trace Table

PassReaderarr[reader]Condition / ActionWriterDelta (reader - writer)Cumulative Moves
0s Left40Match! Bubble to writer=014−0=44 - 0 = 44−0=44
0s Left60Match! Bubble to writer=126−1=56 - 1 = 56−1=59 (Total 0s)
1s Left51Match! Bubble to writer=455−4=15 - 4 = 15−4=11
1s Left71Match! Bubble to writer=567−5=27 - 5 = 27−5=23 (Total 1s)
Final——Return min⁡(9,3)\min(9, 3)min(9,3)——3
Code Shape
Archetype Code Shape
Python
1zero_left = ones_left = 0
2w0 = 0
3while w0 < n and arr[w0] == 0:
4 w0 += 1
5for r in range(w0, n):
6 if arr[r] == 0:
7 zero_left += r - w0
8 w0 += 1
9w1 = 0
10while w1 < n and arr[w1] == 1:
11 w1 += 1
12for r in range(w1, n):
13 if arr[r] == 1:
14 ones_left += r - w1
15 w1 += 1
16return min(zero_left, ones_left)

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 O(Nlog⁡N)O(N \log N)O(NlogN) with a Fenwick tree or Merge Sort, binary elements allow an O(N)O(N)O(N) 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.

🔑 Why It Works

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!

  • 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 += 1 is mandatory to avoid computing swaps to already-occupied slots.

  • Overcomplicating with Fenwick tree or Merge Sort: Inversion count algorithms for arbitrary values take O(Nlog⁡N)O(N \log N)O(NlogN) time and O(N)O(N)O(N) space. Because all values are binary {0, 1}, two-pointer reader-writer simulation solves this in O(N)O(N)O(N) time and O(1)O(1)O(1) space.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

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.

  • 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 and O(1) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

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).

SPACE COMPLEXITY

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.

Formal Recurrence Relation

T(N) = O(N)

Derivation Progression

Zeros-to-Left Compaction Pass

N iterationsN \text{ iterations}N iterations

Scans array accumulating reader - writer for all 0s.

Ones-to-Left Compaction Pass

N iterationsN \text{ iterations}N iterations

Scans array accumulating reader - writer for all 1s.

Total Operations

N + N = 2N = O(N)

Strictly linear time with zero dynamic allocation.

Variable Definitions

NNN

Length of the binary input array

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(1) No heap allocation

🟢 Output Space

O(1) Scalar integer return

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N)

Average Case

O(N)O(N)O(N)

Worst Case

O(N)O(N)O(N)

Pointer Invariant Transition Progression

Pointer Invariant Transition Progression
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

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.

CONSTRAINTS & BOUNDS

1≤n≤1051 \le n \le 10^51≤n≤105, arr[i]∈{0,1}arr[i] \in \{0, 1\}arr[i]∈{0,1}. Requires strictly O(N)O(N)O(N) time and O(1)O(1)O(1) auxiliary space.

FAANG PRODUCTION TRAPS & EDGE CASES

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.

Theory Context•Two Pointers & Sliding Window
HardLC 2193

Minimum Moves to Sort Binary Array (Amazon OA)

Target Frequency:AmazonMicrosoft

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

Example 1
Input:arr = [0, 1, 0, 1]
Output:1
Explanation: With 1 move, switching elements 1 and 2, yields [0, 0, 1, 1], a sorted array.
Example 2
Input:arr = [1, 1, 1, 1, 0, 0, 0, 0]
Output:0
Explanation: The array is already sorted with all 1s on the left and all 0s on the right, so 0 moves are necessary.
Example 3
Input:arr = [1, 1, 1, 1, 0, 1, 0, 1]
Output:3
Explanation: Perform the minimal sequence of 3 moves to sort the array into [1, 1, 1, 1, 1, 1, 0, 0].

⚖️Formal Constraints & Bounds

  • 1 <= n <= 105

  • arr[i] is in the set {0, 1}

Deep-Dive & Conceptual Insights

Core Insight

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

🧩Subproblem 1: Zeros-to-Left Compaction Scan

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.

Mathematical Recurrence / Code Invariant
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 += 1

Step-by-Step Execution Trace Table

PassReaderarr[reader]Condition / ActionWriterDelta (reader - writer)Cumulative Moves
0s Left40Match! Bubble to writer=014−0=44 - 0 = 44−0=44
0s Left60Match! Bubble to writer=126−1=56 - 1 = 56−1=59 (Total 0s)
1s Left51Match! Bubble to writer=455−4=15 - 4 = 15−4=11
1s Left71Match! Bubble to writer=567−5=27 - 5 = 27−5=23 (Total 1s)
Final——Return min⁡(9,3)\min(9, 3)min(9,3)——3
Code Shape
Archetype Code Shape
Python
1zero_left = ones_left = 0
2w0 = 0
3while w0 < n and arr[w0] == 0:
4 w0 += 1
5for r in range(w0, n):
6 if arr[r] == 0:
7 zero_left += r - w0
8 w0 += 1
9w1 = 0
10while w1 < n and arr[w1] == 1:
11 w1 += 1
12for r in range(w1, n):
13 if arr[r] == 1:
14 ones_left += r - w1
15 w1 += 1
16return min(zero_left, ones_left)

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 O(Nlog⁡N)O(N \log N)O(NlogN) with a Fenwick tree or Merge Sort, binary elements allow an O(N)O(N)O(N) 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.

🔑 Why It Works

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!

  • 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 += 1 is mandatory to avoid computing swaps to already-occupied slots.

  • Overcomplicating with Fenwick tree or Merge Sort: Inversion count algorithms for arbitrary values take O(Nlog⁡N)O(N \log N)O(NlogN) time and O(N)O(N)O(N) space. Because all values are binary {0, 1}, two-pointer reader-writer simulation solves this in O(N)O(N)O(N) time and O(1)O(1)O(1) space.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

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.

  • 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 and O(1) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

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).

SPACE COMPLEXITY

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.

Formal Recurrence Relation

T(N) = O(N)

Derivation Progression

Zeros-to-Left Compaction Pass

N iterationsN \text{ iterations}N iterations

Scans array accumulating reader - writer for all 0s.

Ones-to-Left Compaction Pass

N iterationsN \text{ iterations}N iterations

Scans array accumulating reader - writer for all 1s.

Total Operations

N + N = 2N = O(N)

Strictly linear time with zero dynamic allocation.

Variable Definitions

NNN

Length of the binary input array

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(1) No heap allocation

🟢 Output Space

O(1) Scalar integer return

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N)

Average Case

O(N)O(N)O(N)

Worst Case

O(N)O(N)O(N)

Pointer Invariant Transition Progression

Pointer Invariant Transition Progression
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

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.

CONSTRAINTS & BOUNDS

1≤n≤1051 \le n \le 10^51≤n≤105, arr[i]∈{0,1}arr[i] \in \{0, 1\}arr[i]∈{0,1}. Requires strictly O(N)O(N)O(N) time and O(1)O(1)O(1) auxiliary space.

FAANG PRODUCTION TRAPS & EDGE CASES

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.

© 2026 Hi👋WebEnterprise. All rights reserved.
Sitemap•llms.txt•