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)
EasyLC 226

Invert Binary Tree (LeetCode 226)

Target Frequency:GoogleAmazonMeta

You are given the root of a binary tree and must turn it into its mirror image, then hand back its root.

Mirroring a tree means every single node — not just the root — has its left and right child swapped.

Worked Examples

Example 1
Input:root = [4,2,7,1,3,6,9]
Output:[4,7,2,9,6,3,1]
1234679
Explanation: Every node's left and right children are recursively swapped.
Example 2
Input:root = [2,1,3]
Output:[2,3,1]
123
Explanation: Left child 1 and right child 3 are swapped.
Example 3
Input:root = []
Output:[]
Explanation: An empty tree inverted remains empty.

⚖️Formal Constraints & Bounds

  • The number of nodes in the tree is in the range [0, 100].

  • -100 <= Node.val <= 100

Deep-Dive & Conceptual Insights
🔄State Transformation Tree: Invert TreeState Transition
🔵 Original Tree
        [4]
       /        [2]   [7]
     /    /    [1] [3][6] [9]
🟢 Inverted Tree (Mirror Image)
        [4]
       /        [7]   [2]
     /    /    [9] [6][3] [1]

Swapping only the root's children produces (7, 2) but leaves subtrees un-mirrored. Post-order DFS swaps bottom-up: (1, 3) ➔ (3, 1) and (6, 9) ➔ (9, 6), then finally (2, 7) ➔ (7, 2) at root.

Core Insight

In-place pointer swapping modifies the existing tree structure with zero heap allocations.

Real-World Scenario & Production Applications

Transforming right-to-left layout trees for internationalization (RTL UI engines) and 3D graphics mirror transforms.

Step-by-Step Execution Trace Table

StepCall FrameDepthActionChildren BeforeChildren After (Swap)Rationale
1Node 4d=1⬇️ ENTER(2, 7)—Suspends; subtrees must invert before root can swap.
2Node 2d=2⬇️ ENTER(1, 3)—Descend left subtree.
3Node 1d=3⬇️↑ VISIT(None, None)(None, None)Leaf: swapping (None, None) is identity.
4Node 3d=3⬇️↑ VISIT(None, None)(None, None)Leaf: identity.
5Node 2d=2↑ SWAP(1, 3)(3, 1)Post-order combine: swap children of 2.
6Node 7d=2⬇️ ENTER(6, 9)—Descend right subtree of root.
7Node 6d=3⬇️↑ VISIT(None, None)(None, None)Leaf: identity.
8Node 9d=3⬇️↑ VISIT(None, None)(None, None)Leaf: identity.
9Node 7d=2↑ SWAP(6, 9)(9, 6)Post-order combine: swap children of 7.
10Node 4d=1↑ SWAP & FINISH(2, 7)(7, 2)Swap fully inverted subtrees with O(1)O(1)O(1) pointer swap!
Trace Inputroot = [4,2,7,1,3,6,9]
Expected[4,7,2,9,6,3,1]
StepCall FrameDepthActionChildren BeforeChildren After (Swap)Rationale
1Node 4d=1⬇️ ENTER(2, 7)—Suspends; subtrees must invert before root can swap.
2Node 2d=2⬇️ ENTER(1, 3)—Descend left subtree.
3Node 1d=3⬇️↑ VISIT(None, None)(None, None)Leaf: swapping (None, None) is identity.
4Node 3d=3⬇️↑ VISIT(None, None)(None, None)Leaf: identity.
5Node 2d=2↑ SWAP(1, 3)(3, 1)Post-order combine: swap children of 2.
6Node 7d=2⬇️ ENTER(6, 9)—Descend right subtree of root.
7Node 6d=3⬇️↑ VISIT(None, None)(None, None)Leaf: identity.
8Node 9d=3⬇️↑ VISIT(None, None)(None, None)Leaf: identity.
9Node 7d=2↑ SWAP(6, 9)(9, 6)Post-order combine: swap children of 7.
10Node 4d=1↑ SWAP & FINISH(2, 7)(7, 2)Swap fully inverted subtrees with O(1)O(1)O(1) pointer swap!
Code Shape
Archetype Code Shape
Python
1if not root:
2 return None
3invertTree(root.left)
4invertTree(root.right)
5root.left, root.right = root.right, root.left
6return root

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Inverting a binary tree (creating its mirror image) is the quintessential example of tree structural mutation. For every node in the tree, its left child pointer and right child pointer must swap identities. This swap must propagate down every level until reaching the leaves. Because tree mutations can easily overwrite child references before they are visited, understanding the call stack's order of execution is crucial to avoiding corrupted tree structures.

🏟️ The Analogy: The Photographer and the Hall of Mirrors

Imagine a family standing in a pyramid formation for a portrait. To create a perfect mirror image of the photograph, you don't dismantle the people. You simply ask each parent to swap the positions of their left child and right child. The parents swap their kids' places, and then each child who is also a parent swaps their own children's places. Once every parent has swapped their two children, the entire family tree is perfectly mirrored.

🔑 Why It Works

Notice how Python's simultaneous assignment root.left, root.right = root.right, root.left eliminates the need for temporary pointer buffers. Whether you swap pointers before recursing (pre-order) or after recursing (post-order), every node's children are flipped exactly once in O(N)O(N)O(N) time.

  • Overwriting unvisited subtree pointers: In languages without tuple unpacking (root.left, root.right = root.right, root.left), writing root.left = invert(root.right) overwrites root.left before it can be traversed, duplicating the right subtree.

  • Inverting subtrees twice: Calling invert on the children before or after swapping must be done consistently; doing both inverts the tree back to its original shape.

  • Failing on empty tree base case: Forgetting if not root: return None causes AttributeError on empty inputs or leaf child visits.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Binary tree + structural mirror transformation.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: each node swaps its left and right pointers after their subtrees have been recursively inverted.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

This problem's traps are in Common Pitfalls above.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I recursively invert the left and right subtrees, then swap the left and right pointers of the current node. This inverts the tree in O(N) time and O(H) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the execution steps: Visits every node once, swapping its left and right child pointers in O(1) operations per node.

SPACE COMPLEXITY

O(H) Auxiliary

Recursion stack depth equals tree height H.

Formal Recurrence Relation

T(N) = 2T(N/2) + O(1) = O(N)

Derivation Progression

Child Pointer Swap

node.left, node.right = invert(right), invert(left)

Swaps left and right pointers in-place at each node.

Full Tree Walk

N node visits

Every node is visited and transformed exactly once.

Linear Bound

O(N) total time

Direct linear scan through the tree structure.

Variable Definitions

NNN

Total number of nodes in the binary tree

HHH

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

Memory Architecture & Bounds

🟣 Call Stack

O(H) Call stack frames (H in [log N, N])

🔵 Auxiliary Heap

O(1) In-place node mutation

🟢 Output Space

O(1) Root reference

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N) time, O(log⁡N)O(\log N)O(logN) space.

Average Case

O(N)O(N)O(N) time, O(log⁡N)O(\log N)O(logN) space.

Worst Case

O(N)O(N)O(N) time, O(N)O(N)O(N) space.

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: "invert a binary tree", "mirror binary tree". Mutate-in-place structural transformation: at every node in the tree, swap its left and right child pointers, then recursively invert both subtrees.

CONSTRAINTS & BOUNDS

0≤N≤1000 \le N \le 1000≤N≤100. Operates in O(N)O(N)O(N) time with O(H)O(H)O(H) call stack.

FAANG PRODUCTION TRAPS & EDGE CASES

Overwriting child references before recursion: in Python, tuple unpacking node.left, node.right = self.invertTree(node.right), self.invertTree(node.left) cleanly prevents stale pointer bugs.

Theory Context•Depth-First Search (DFS)
EasyLC 226

Invert Binary Tree (LeetCode 226)

Target Frequency:GoogleAmazonMeta

You are given the root of a binary tree and must turn it into its mirror image, then hand back its root.

Mirroring a tree means every single node — not just the root — has its left and right child swapped.

Worked Examples

Example 1
Input:root = [4,2,7,1,3,6,9]
Output:[4,7,2,9,6,3,1]
1234679
Explanation: Every node's left and right children are recursively swapped.
Example 2
Input:root = [2,1,3]
Output:[2,3,1]
123
Explanation: Left child 1 and right child 3 are swapped.
Example 3
Input:root = []
Output:[]
Explanation: An empty tree inverted remains empty.

⚖️Formal Constraints & Bounds

  • The number of nodes in the tree is in the range [0, 100].

  • -100 <= Node.val <= 100

Deep-Dive & Conceptual Insights
🔄State Transformation Tree: Invert TreeState Transition
🔵 Original Tree
        [4]
       /        [2]   [7]
     /    /    [1] [3][6] [9]
🟢 Inverted Tree (Mirror Image)
        [4]
       /        [7]   [2]
     /    /    [9] [6][3] [1]

Swapping only the root's children produces (7, 2) but leaves subtrees un-mirrored. Post-order DFS swaps bottom-up: (1, 3) ➔ (3, 1) and (6, 9) ➔ (9, 6), then finally (2, 7) ➔ (7, 2) at root.

Core Insight

In-place pointer swapping modifies the existing tree structure with zero heap allocations.

Real-World Scenario & Production Applications

Transforming right-to-left layout trees for internationalization (RTL UI engines) and 3D graphics mirror transforms.

Step-by-Step Execution Trace Table

StepCall FrameDepthActionChildren BeforeChildren After (Swap)Rationale
1Node 4d=1⬇️ ENTER(2, 7)—Suspends; subtrees must invert before root can swap.
2Node 2d=2⬇️ ENTER(1, 3)—Descend left subtree.
3Node 1d=3⬇️↑ VISIT(None, None)(None, None)Leaf: swapping (None, None) is identity.
4Node 3d=3⬇️↑ VISIT(None, None)(None, None)Leaf: identity.
5Node 2d=2↑ SWAP(1, 3)(3, 1)Post-order combine: swap children of 2.
6Node 7d=2⬇️ ENTER(6, 9)—Descend right subtree of root.
7Node 6d=3⬇️↑ VISIT(None, None)(None, None)Leaf: identity.
8Node 9d=3⬇️↑ VISIT(None, None)(None, None)Leaf: identity.
9Node 7d=2↑ SWAP(6, 9)(9, 6)Post-order combine: swap children of 7.
10Node 4d=1↑ SWAP & FINISH(2, 7)(7, 2)Swap fully inverted subtrees with O(1)O(1)O(1) pointer swap!
Trace Inputroot = [4,2,7,1,3,6,9]
Expected[4,7,2,9,6,3,1]
StepCall FrameDepthActionChildren BeforeChildren After (Swap)Rationale
1Node 4d=1⬇️ ENTER(2, 7)—Suspends; subtrees must invert before root can swap.
2Node 2d=2⬇️ ENTER(1, 3)—Descend left subtree.
3Node 1d=3⬇️↑ VISIT(None, None)(None, None)Leaf: swapping (None, None) is identity.
4Node 3d=3⬇️↑ VISIT(None, None)(None, None)Leaf: identity.
5Node 2d=2↑ SWAP(1, 3)(3, 1)Post-order combine: swap children of 2.
6Node 7d=2⬇️ ENTER(6, 9)—Descend right subtree of root.
7Node 6d=3⬇️↑ VISIT(None, None)(None, None)Leaf: identity.
8Node 9d=3⬇️↑ VISIT(None, None)(None, None)Leaf: identity.
9Node 7d=2↑ SWAP(6, 9)(9, 6)Post-order combine: swap children of 7.
10Node 4d=1↑ SWAP & FINISH(2, 7)(7, 2)Swap fully inverted subtrees with O(1)O(1)O(1) pointer swap!
Code Shape
Archetype Code Shape
Python
1if not root:
2 return None
3invertTree(root.left)
4invertTree(root.right)
5root.left, root.right = root.right, root.left
6return root

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Inverting a binary tree (creating its mirror image) is the quintessential example of tree structural mutation. For every node in the tree, its left child pointer and right child pointer must swap identities. This swap must propagate down every level until reaching the leaves. Because tree mutations can easily overwrite child references before they are visited, understanding the call stack's order of execution is crucial to avoiding corrupted tree structures.

🏟️ The Analogy: The Photographer and the Hall of Mirrors

Imagine a family standing in a pyramid formation for a portrait. To create a perfect mirror image of the photograph, you don't dismantle the people. You simply ask each parent to swap the positions of their left child and right child. The parents swap their kids' places, and then each child who is also a parent swaps their own children's places. Once every parent has swapped their two children, the entire family tree is perfectly mirrored.

🔑 Why It Works

Notice how Python's simultaneous assignment root.left, root.right = root.right, root.left eliminates the need for temporary pointer buffers. Whether you swap pointers before recursing (pre-order) or after recursing (post-order), every node's children are flipped exactly once in O(N)O(N)O(N) time.

  • Overwriting unvisited subtree pointers: In languages without tuple unpacking (root.left, root.right = root.right, root.left), writing root.left = invert(root.right) overwrites root.left before it can be traversed, duplicating the right subtree.

  • Inverting subtrees twice: Calling invert on the children before or after swapping must be done consistently; doing both inverts the tree back to its original shape.

  • Failing on empty tree base case: Forgetting if not root: return None causes AttributeError on empty inputs or leaf child visits.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Binary tree + structural mirror transformation.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: each node swaps its left and right pointers after their subtrees have been recursively inverted.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

This problem's traps are in Common Pitfalls above.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I recursively invert the left and right subtrees, then swap the left and right pointers of the current node. This inverts the tree in O(N) time and O(H) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the execution steps: Visits every node once, swapping its left and right child pointers in O(1) operations per node.

SPACE COMPLEXITY

O(H) Auxiliary

Recursion stack depth equals tree height H.

Formal Recurrence Relation

T(N) = 2T(N/2) + O(1) = O(N)

Derivation Progression

Child Pointer Swap

node.left, node.right = invert(right), invert(left)

Swaps left and right pointers in-place at each node.

Full Tree Walk

N node visits

Every node is visited and transformed exactly once.

Linear Bound

O(N) total time

Direct linear scan through the tree structure.

Variable Definitions

NNN

Total number of nodes in the binary tree

HHH

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

Memory Architecture & Bounds

🟣 Call Stack

O(H) Call stack frames (H in [log N, N])

🔵 Auxiliary Heap

O(1) In-place node mutation

🟢 Output Space

O(1) Root reference

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N) time, O(log⁡N)O(\log N)O(logN) space.

Average Case

O(N)O(N)O(N) time, O(log⁡N)O(\log N)O(logN) space.

Worst Case

O(N)O(N)O(N) time, O(N)O(N)O(N) space.

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: "invert a binary tree", "mirror binary tree". Mutate-in-place structural transformation: at every node in the tree, swap its left and right child pointers, then recursively invert both subtrees.

CONSTRAINTS & BOUNDS

0≤N≤1000 \le N \le 1000≤N≤100. Operates in O(N)O(N)O(N) time with O(H)O(H)O(H) call stack.

FAANG PRODUCTION TRAPS & EDGE CASES

Overwriting child references before recursion: in Python, tuple unpacking node.left, node.right = self.invertTree(node.right), self.invertTree(node.left) cleanly prevents stale pointer bugs.

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