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•Depth-First Search (DFS)
MediumLC 979

Distribute Coins in Binary Tree (LeetCode 979)

Target Frequency:GoogleAmazonMeta

You're given the root of an n-node binary tree where each node is holding node.val coins, and the coins across the whole tree add up to exactly n.

A move slides a single coin between two nodes that are directly connected — parent to child, or child to parent.

Work out the minimum number of moves needed so every node ends up holding exactly one coin.

Worked Examples

Example 1
Input:root = [3,0,0]
Output:2
030
Explanation: The root starts with three coins and sends one down to each of its two children, two moves in total.
Example 2
Input:root = [0,3,0]
Output:3
300
Explanation: The left child starts with three coins: two of them move up to the root (two moves), and one of those then continues down to the right child, three moves overall.

⚖️Formal Constraints & Bounds

  • The number of nodes in the tree is n.

  • 1 <= n <= 100

  • 0 <= Node.val <= n

  • The sum of all Node.val is n.

Deep-Dive & Conceptual Insights

Core Insight

Every subtree's excess (coins minus nodes) must cross the single edge to its parent -- the direction doesn't matter, only the magnitude. Postorder DFS accumulates abs(left_excess) + abs(right_excess) at every node and returns node.val + left + right - 1 (the -1 accounts for this node keeping one coin for itself).

Real-World Scenario & Production Applications

Load-balancing resource redistribution across a hierarchical server topology, minimum-transfer inventory rebalancing across a warehouse tree network.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Empty Subtree Has Zero Excess

A null child holds no coins and needs none, so it reports an excess of 0.

Mathematical Recurrence / Code Invariant
if node is None:
    return 0
Code Shape
Archetype Code Shape
Python
1if not node:
2 return 0
3left = excess(node.left)
4right = excess(node.right)
5moves += abs(left) + abs(right)
6return node.val + left + right - 1

Conceptual Narrative

🧠 Pattern Intuition & Real-World Analogy

This is the "Supply and Demand" sibling of Binary Tree Cameras: instead of a discrete tri-state code, each subtree reports a signed quantity — how much surplus or shortage of coins it is carrying — and every edge pays for the imbalance that crosses it.

🏦 The Analogy: A Chain of Branch Banks Settling Cash Imbalances

Imagine a hierarchy of bank branches, each starting the day with some amount of cash and each needing to end the day with exactly one unit in its own till. Each branch first settles its own child branches: any branch with too much cash sends its surplus down to headquarters via the one road connecting them (or asks for more if it's short), and every unit that travels along that specific road counts as one "move," regardless of which direction it travels. Once a branch has settled up with all of its children, whatever surplus or shortage remains rolls up to be handled with its own parent branch, one level higher.

🔑 The Key Idea in the Code

abs(left) + abs(right) is the entire trick: it doesn't matter whether a child subtree has too many coins (positive excess, coins flow down-to-up) or too few (negative excess, coins flow up-to-down) — either way, exactly abs(excess) coins must cross that one edge, so the move count only cares about magnitude, never sign.

  • Forgetting the - 1 term: Returning node.val + left + right instead of node.val + left + right - 1. Each node keeps exactly one coin for itself before reporting its surplus or deficit upward; omitting the -1 silently double-counts every node's own coin.

  • Treating a deficit as free: Only accumulating moves when left/right is positive (surplus flowing up) and skipping negative excess (a deficit flowing down). The direction a coin travels across an edge doesn't matter for counting moves -- abs(left) + abs(right) must be accumulated regardless of sign.

  • Accumulating moves at the wrong node: Adding abs(left) + abs(right) from inside the child's own call instead of at the parent, after both children have returned. Each edge's cost is charged exactly once, at the parent that receives the child's excess.

  • Forgetting the global counter is order-independent: Assuming coins must physically move in a particular sequence to achieve the minimum count. The postorder sum of abs(excess) over every edge is provably optimal regardless of the order moves are actually performed in.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Exactly one coin per node, minimum number of moves sliding a coin along an edge between adjacent nodes.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: a subtree with signed excess k (surplus if positive, deficit if negative) must move exactly |k| coins across the single edge to its parent.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • The card's trap: return the signed surplus and take abs only when adding to moves.

  • The root's own excess is always 0 (the tree has as many coins as nodes), so returning excess(root) instead of moves returns 0.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use Greedy Tree DP. Coins can only enter or leave a subtree through the one edge to its parent, so for every subtree I compute its surplus: the coins it holds minus the number of nodes, which is the node's coins plus both children's surpluses minus one for the node itself. Whatever that number is, that many coins must cross the edge above the subtree, in one direction or the other, and settling each subtree with its parent in postorder never moves more than that. So at each node I add the absolute values of the two children's surpluses to the move count, and return my own signed surplus. The trap is where the absolute value goes: if I returned it, a subtree that is short two coins would look like it had two to spare. The answer is the move count, not the root's surplus, which is always zero. It's O(N) time and O(H) recursion stack.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at excess(node): each node is visited once and does O(1) arithmetic — two absolute values, one addition to moves, and one return value. No coin move is ever simulated; moves are counted from excess magnitudes.

SPACE COMPLEXITY

O(H) Auxiliary

The recursion stack holds one frame per level of the current path, so auxiliary space is the tree height H. moves is a single integer.

Formal Recurrence Relation

T(N) = N · O(1) = O(N)

Derivation Progression

Postorder Visit

N node visits

Every node is entered once, after both children return their excess.

O(1) Work Per Frame

moves += |left| + |right|

Each edge's cost is its child's excess magnitude, added once.

Total Time

O(N)

N frames with constant work each.

Variable Definitions

NNN

Total number of nodes (and coins) in the tree

HHH

Tree height (log N in a balanced tree, N in a skewed tree)

Memory Architecture & Bounds

🟣 Call Stack

O(H) recursion frames

🔵 Auxiliary Heap

O(1) move counter

🟢 Output Space

O(1) returns one integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N) time with O(log⁡N)O(\log N)O(logN) stack on a balanced tree.

Average Case

O(N)O(N)O(N) time.

Worst Case

O(N)O(N)O(N) time with O(N)O(N)O(N) stack on a skewed tree.

Graph & Tree Traversal Frontier

Graph & Tree Traversal Frontier
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "exactly one coin per node", "minimum number of moves", "slide a coin along an edge". Postorder Excess/Deficit Balancing: every subtree reports a signed "excess" (coins minus nodes) to its parent; total work is ∑∣excess∣\sum |excess|∑∣excess∣ over every edge.

CONSTRAINTS & BOUNDS

N≤100N \le 100N≤100. Time budget is strictly O(N)O(N)O(N), one postorder pass.

FAANG PRODUCTION TRAPS & EDGE CASES

At LeetCode's n≤100n \le 100n≤100 recursion is safe, but a deep hierarchy of thousands of levels passes CPython's default recursion limit of 1000: run the same postorder with an explicit stack.

Theory Context•Depth-First Search (DFS)
MediumLC 979

Distribute Coins in Binary Tree (LeetCode 979)

Target Frequency:GoogleAmazonMeta

You're given the root of an n-node binary tree where each node is holding node.val coins, and the coins across the whole tree add up to exactly n.

A move slides a single coin between two nodes that are directly connected — parent to child, or child to parent.

Work out the minimum number of moves needed so every node ends up holding exactly one coin.

Worked Examples

Example 1
Input:root = [3,0,0]
Output:2
030
Explanation: The root starts with three coins and sends one down to each of its two children, two moves in total.
Example 2
Input:root = [0,3,0]
Output:3
300
Explanation: The left child starts with three coins: two of them move up to the root (two moves), and one of those then continues down to the right child, three moves overall.

⚖️Formal Constraints & Bounds

  • The number of nodes in the tree is n.

  • 1 <= n <= 100

  • 0 <= Node.val <= n

  • The sum of all Node.val is n.

Deep-Dive & Conceptual Insights

Core Insight

Every subtree's excess (coins minus nodes) must cross the single edge to its parent -- the direction doesn't matter, only the magnitude. Postorder DFS accumulates abs(left_excess) + abs(right_excess) at every node and returns node.val + left + right - 1 (the -1 accounts for this node keeping one coin for itself).

Real-World Scenario & Production Applications

Load-balancing resource redistribution across a hierarchical server topology, minimum-transfer inventory rebalancing across a warehouse tree network.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Empty Subtree Has Zero Excess

A null child holds no coins and needs none, so it reports an excess of 0.

Mathematical Recurrence / Code Invariant
if node is None:
    return 0
Code Shape
Archetype Code Shape
Python
1if not node:
2 return 0
3left = excess(node.left)
4right = excess(node.right)
5moves += abs(left) + abs(right)
6return node.val + left + right - 1

Conceptual Narrative

🧠 Pattern Intuition & Real-World Analogy

This is the "Supply and Demand" sibling of Binary Tree Cameras: instead of a discrete tri-state code, each subtree reports a signed quantity — how much surplus or shortage of coins it is carrying — and every edge pays for the imbalance that crosses it.

🏦 The Analogy: A Chain of Branch Banks Settling Cash Imbalances

Imagine a hierarchy of bank branches, each starting the day with some amount of cash and each needing to end the day with exactly one unit in its own till. Each branch first settles its own child branches: any branch with too much cash sends its surplus down to headquarters via the one road connecting them (or asks for more if it's short), and every unit that travels along that specific road counts as one "move," regardless of which direction it travels. Once a branch has settled up with all of its children, whatever surplus or shortage remains rolls up to be handled with its own parent branch, one level higher.

🔑 The Key Idea in the Code

abs(left) + abs(right) is the entire trick: it doesn't matter whether a child subtree has too many coins (positive excess, coins flow down-to-up) or too few (negative excess, coins flow up-to-down) — either way, exactly abs(excess) coins must cross that one edge, so the move count only cares about magnitude, never sign.

  • Forgetting the - 1 term: Returning node.val + left + right instead of node.val + left + right - 1. Each node keeps exactly one coin for itself before reporting its surplus or deficit upward; omitting the -1 silently double-counts every node's own coin.

  • Treating a deficit as free: Only accumulating moves when left/right is positive (surplus flowing up) and skipping negative excess (a deficit flowing down). The direction a coin travels across an edge doesn't matter for counting moves -- abs(left) + abs(right) must be accumulated regardless of sign.

  • Accumulating moves at the wrong node: Adding abs(left) + abs(right) from inside the child's own call instead of at the parent, after both children have returned. Each edge's cost is charged exactly once, at the parent that receives the child's excess.

  • Forgetting the global counter is order-independent: Assuming coins must physically move in a particular sequence to achieve the minimum count. The postorder sum of abs(excess) over every edge is provably optimal regardless of the order moves are actually performed in.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Exactly one coin per node, minimum number of moves sliding a coin along an edge between adjacent nodes.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: a subtree with signed excess k (surplus if positive, deficit if negative) must move exactly |k| coins across the single edge to its parent.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • The card's trap: return the signed surplus and take abs only when adding to moves.

  • The root's own excess is always 0 (the tree has as many coins as nodes), so returning excess(root) instead of moves returns 0.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use Greedy Tree DP. Coins can only enter or leave a subtree through the one edge to its parent, so for every subtree I compute its surplus: the coins it holds minus the number of nodes, which is the node's coins plus both children's surpluses minus one for the node itself. Whatever that number is, that many coins must cross the edge above the subtree, in one direction or the other, and settling each subtree with its parent in postorder never moves more than that. So at each node I add the absolute values of the two children's surpluses to the move count, and return my own signed surplus. The trap is where the absolute value goes: if I returned it, a subtree that is short two coins would look like it had two to spare. The answer is the move count, not the root's surplus, which is always zero. It's O(N) time and O(H) recursion stack.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at excess(node): each node is visited once and does O(1) arithmetic — two absolute values, one addition to moves, and one return value. No coin move is ever simulated; moves are counted from excess magnitudes.

SPACE COMPLEXITY

O(H) Auxiliary

The recursion stack holds one frame per level of the current path, so auxiliary space is the tree height H. moves is a single integer.

Formal Recurrence Relation

T(N) = N · O(1) = O(N)

Derivation Progression

Postorder Visit

N node visits

Every node is entered once, after both children return their excess.

O(1) Work Per Frame

moves += |left| + |right|

Each edge's cost is its child's excess magnitude, added once.

Total Time

O(N)

N frames with constant work each.

Variable Definitions

NNN

Total number of nodes (and coins) in the tree

HHH

Tree height (log N in a balanced tree, N in a skewed tree)

Memory Architecture & Bounds

🟣 Call Stack

O(H) recursion frames

🔵 Auxiliary Heap

O(1) move counter

🟢 Output Space

O(1) returns one integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N) time with O(log⁡N)O(\log N)O(logN) stack on a balanced tree.

Average Case

O(N)O(N)O(N) time.

Worst Case

O(N)O(N)O(N) time with O(N)O(N)O(N) stack on a skewed tree.

Graph & Tree Traversal Frontier

Graph & Tree Traversal Frontier
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "exactly one coin per node", "minimum number of moves", "slide a coin along an edge". Postorder Excess/Deficit Balancing: every subtree reports a signed "excess" (coins minus nodes) to its parent; total work is ∑∣excess∣\sum |excess|∑∣excess∣ over every edge.

CONSTRAINTS & BOUNDS

N≤100N \le 100N≤100. Time budget is strictly O(N)O(N)O(N), one postorder pass.

FAANG PRODUCTION TRAPS & EDGE CASES

At LeetCode's n≤100n \le 100n≤100 recursion is safe, but a deep hierarchy of thousands of levels passes CPython's default recursion limit of 1000: run the same postorder with an explicit stack.

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