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 701

Insert into a Binary Search Tree (LeetCode 701)

Target Frequency:AmazonMicrosoft

You're handed the root of a binary search tree (BST) plus a value that needs a home in it. Splice the value in and hand back the root of the updated BST. The value is guaranteed to be new — it isn't already in the tree.

There's often more than one legal spot for the new node; any placement that keeps the BST ordering intact is accepted.

Worked Examples

Example 1
Input:root = [4,2,7,1,3], val = 5
Output:[4,2,7,1,3,5]
12347
Explanation: 5 is bigger than 4 and smaller than 7, so it becomes 7's left child. Other valid BSTs that contain 5 are accepted too.
Example 2
Input:root = [40,20,60,10,30,50,70], val = 25
Output:[40,20,60,10,30,50,70,null,null,25]
10203040506070
Explanation: 25 goes left of 40, right of 20, then into the empty left spot under 30.
Example 3
Input:root = [4,2,7,1,3,null,null,null,null,null,null], val = 5
Output:[4,2,7,1,3,5]
12347
Explanation: 5 is bigger than 4 and smaller than 7, so it becomes 7's left child.

⚖️Formal Constraints & Bounds

  • The number of nodes in the tree will be in the range [0, 104].

  • -108 <= Node.val <= 108

  • All the values Node.val are unique.

  • -108 <= val <= 108

  • It's guaranteed that val does not exist in the original BST.

Deep-Dive & Conceptual Insights

Core Insight

Re-assigning child pointers root.left = insert(root.left, val) cleanly updates tree topology without parent pointers.

Real-World Scenario & Production Applications

Dynamic symbol table updates, fast key insertion in database trees.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Base Case -- Empty Slot Found

Recursing past a leaf's child lands on None -- that's exactly where the new value belongs, so a fresh TreeNode(val) is returned to be spliced in by the parent frame.

Mathematical Recurrence / Code Invariant
if not root:
    return TreeNode(val)

Step-by-Step Execution Trace Table

Current NodeComparison vs val=5Action
45 > 4Recurse right to node 7
75 < 7Recurse left to null
NoneBase caseReturn TreeNode(5) -> node7.left = TreeNode(5)
Trace Inputroot = [4,2,7,1,3], val = 5
Expected[4,2,7,1,3,5]
Current NodeComparison vs val=5Action
45 > 4Recurse right to node 7
75 < 7Recurse left to null
NoneBase caseReturn TreeNode(5) -> node7.left = TreeNode(5)
Code Shape
Archetype Code Shape
Python
1if not root:
2 return TreeNode(val)
3if val < root.val:
4 root.left = insertIntoBST(root.left, val)
5else:
6 root.right = insertIntoBST(root.right, val)
7return root

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

A Binary Search Tree (BST) enforces a strict spatial contract: for every node, all values in its left subtree are strictly smaller than its own value, and all values in its right subtree are strictly larger. Inserting a new value into a BST never requires rebalancing or rearranging existing nodes. Because the tree's ordering invariant is absolute, there exists a unique empty slot (a null pointer at a leaf boundary) where the new value naturally belongs. The search for this slot is completely deterministic, running in O(H)O(H)O(H) time where HHH is the tree height.

🏟️ The Analogy: Parking in an Automated Valet Garage

Imagine driving into a tiered valet garage where cars are sorted by size. At the entrance gate, a scanner checks your car length. If your car is smaller than the gate's reference car, an automated sign directs you: "Turn Left". At the next intersection, your car is compared again. If it is larger, the sign directs: "Turn Right". You continue following the binary directional signs at each junction until you reach an empty designated parking stall at the end of the aisle. You park in that vacant spot without moving any other vehicle.

🔑 Why It Works

The recursive pattern root.left = insert(root.left, val) is the "pointer reconnection idiom". At the leaf boundary, the base case creates and returns the new node. The parent node reassigns its null pointer to this new child, while all ancestor nodes simply reconnect their existing subtrees unharmed as recursion unwinds.

  • Severing child links on recursion: Writing root.left = insertIntoBST(root.left, val) is clean, but forgetting to return root at the end returns None to parent callers.

  • Inserting duplicates into BST: If val == root.val, standard BST insertion must specify behavior (usually inserting right or disallowing duplicates).

  • Base case allocation: The base case if not root: return TreeNode(val) must create the new leaf node and return it to be attached.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

BST dynamic insertion while maintaining sorted tree topology.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: re-linking root.left = insert(root.left, val) preserves the BST invariant along the search path.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Modifying root reference instead of re-linking child pointers.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I compare val against root.val. If val < root.val, I recursively insert into left subtree and re-link root.left; otherwise into right subtree. When root is None, I return TreeNode(val). Runs in O(H) time and O(H) call-stack space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(H)

Look at the execution steps: Traverses single path from root to leaf by comparing val with node.val in O(1) time. Inserts new TreeNode at leaf. Path length equals tree height H.

SPACE COMPLEXITY

O(H) Auxiliary

Call stack depth equals tree height H (or O(1) space if implemented iteratively).

Formal Recurrence Relation

T(H) = H comparisons = O(H)

Derivation Progression

Directional Branching

if val < node.val: go left else go right

Follows unique path down the BST in O(1) comparison per level.

Leaf Attachment

node.left/right = TreeNode(val)

Attaches new node at leaf position in O(1) pointer assignment.

Path Depth Bound

H ≤ N ⟹ O(H)

Runs in time proportional to tree height.

Variable Definitions

NNN

Total number of nodes in the BST

HHH

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

Memory Architecture & Bounds

🟣 Call Stack

O(H) Recursive stack frames (O(1) if iterative)

🔵 Auxiliary Heap

O(1) One new TreeNode allocation

🟢 Output Space

O(1) Root reference

Boundary Best / Worst Cases

Best Case

O(1)O(1)O(1) if inserting into empty root, O(log⁡N)O(\log N)O(logN) on balanced BST.

Average Case

O(log⁡N)O(\log N)O(logN).

Worst Case

O(N)O(N)O(N) on degenerate 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: "insert into a binary search tree". Functional recursive tree splicing: the function returns the root of the modified subtree.

CONSTRAINTS & BOUNDS

N≤104N \le 10^4N≤104, values distinct. Time budget O(H)O(H)O(H) where H≤NH \le NH≤N.

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

Insert into a Binary Search Tree (LeetCode 701)

Target Frequency:AmazonMicrosoft

You're handed the root of a binary search tree (BST) plus a value that needs a home in it. Splice the value in and hand back the root of the updated BST. The value is guaranteed to be new — it isn't already in the tree.

There's often more than one legal spot for the new node; any placement that keeps the BST ordering intact is accepted.

Worked Examples

Example 1
Input:root = [4,2,7,1,3], val = 5
Output:[4,2,7,1,3,5]
12347
Explanation: 5 is bigger than 4 and smaller than 7, so it becomes 7's left child. Other valid BSTs that contain 5 are accepted too.
Example 2
Input:root = [40,20,60,10,30,50,70], val = 25
Output:[40,20,60,10,30,50,70,null,null,25]
10203040506070
Explanation: 25 goes left of 40, right of 20, then into the empty left spot under 30.
Example 3
Input:root = [4,2,7,1,3,null,null,null,null,null,null], val = 5
Output:[4,2,7,1,3,5]
12347
Explanation: 5 is bigger than 4 and smaller than 7, so it becomes 7's left child.

⚖️Formal Constraints & Bounds

  • The number of nodes in the tree will be in the range [0, 104].

  • -108 <= Node.val <= 108

  • All the values Node.val are unique.

  • -108 <= val <= 108

  • It's guaranteed that val does not exist in the original BST.

Deep-Dive & Conceptual Insights

Core Insight

Re-assigning child pointers root.left = insert(root.left, val) cleanly updates tree topology without parent pointers.

Real-World Scenario & Production Applications

Dynamic symbol table updates, fast key insertion in database trees.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Base Case -- Empty Slot Found

Recursing past a leaf's child lands on None -- that's exactly where the new value belongs, so a fresh TreeNode(val) is returned to be spliced in by the parent frame.

Mathematical Recurrence / Code Invariant
if not root:
    return TreeNode(val)

Step-by-Step Execution Trace Table

Current NodeComparison vs val=5Action
45 > 4Recurse right to node 7
75 < 7Recurse left to null
NoneBase caseReturn TreeNode(5) -> node7.left = TreeNode(5)
Trace Inputroot = [4,2,7,1,3], val = 5
Expected[4,2,7,1,3,5]
Current NodeComparison vs val=5Action
45 > 4Recurse right to node 7
75 < 7Recurse left to null
NoneBase caseReturn TreeNode(5) -> node7.left = TreeNode(5)
Code Shape
Archetype Code Shape
Python
1if not root:
2 return TreeNode(val)
3if val < root.val:
4 root.left = insertIntoBST(root.left, val)
5else:
6 root.right = insertIntoBST(root.right, val)
7return root

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

A Binary Search Tree (BST) enforces a strict spatial contract: for every node, all values in its left subtree are strictly smaller than its own value, and all values in its right subtree are strictly larger. Inserting a new value into a BST never requires rebalancing or rearranging existing nodes. Because the tree's ordering invariant is absolute, there exists a unique empty slot (a null pointer at a leaf boundary) where the new value naturally belongs. The search for this slot is completely deterministic, running in O(H)O(H)O(H) time where HHH is the tree height.

🏟️ The Analogy: Parking in an Automated Valet Garage

Imagine driving into a tiered valet garage where cars are sorted by size. At the entrance gate, a scanner checks your car length. If your car is smaller than the gate's reference car, an automated sign directs you: "Turn Left". At the next intersection, your car is compared again. If it is larger, the sign directs: "Turn Right". You continue following the binary directional signs at each junction until you reach an empty designated parking stall at the end of the aisle. You park in that vacant spot without moving any other vehicle.

🔑 Why It Works

The recursive pattern root.left = insert(root.left, val) is the "pointer reconnection idiom". At the leaf boundary, the base case creates and returns the new node. The parent node reassigns its null pointer to this new child, while all ancestor nodes simply reconnect their existing subtrees unharmed as recursion unwinds.

  • Severing child links on recursion: Writing root.left = insertIntoBST(root.left, val) is clean, but forgetting to return root at the end returns None to parent callers.

  • Inserting duplicates into BST: If val == root.val, standard BST insertion must specify behavior (usually inserting right or disallowing duplicates).

  • Base case allocation: The base case if not root: return TreeNode(val) must create the new leaf node and return it to be attached.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

BST dynamic insertion while maintaining sorted tree topology.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: re-linking root.left = insert(root.left, val) preserves the BST invariant along the search path.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Modifying root reference instead of re-linking child pointers.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I compare val against root.val. If val < root.val, I recursively insert into left subtree and re-link root.left; otherwise into right subtree. When root is None, I return TreeNode(val). Runs in O(H) time and O(H) call-stack space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(H)

Look at the execution steps: Traverses single path from root to leaf by comparing val with node.val in O(1) time. Inserts new TreeNode at leaf. Path length equals tree height H.

SPACE COMPLEXITY

O(H) Auxiliary

Call stack depth equals tree height H (or O(1) space if implemented iteratively).

Formal Recurrence Relation

T(H) = H comparisons = O(H)

Derivation Progression

Directional Branching

if val < node.val: go left else go right

Follows unique path down the BST in O(1) comparison per level.

Leaf Attachment

node.left/right = TreeNode(val)

Attaches new node at leaf position in O(1) pointer assignment.

Path Depth Bound

H ≤ N ⟹ O(H)

Runs in time proportional to tree height.

Variable Definitions

NNN

Total number of nodes in the BST

HHH

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

Memory Architecture & Bounds

🟣 Call Stack

O(H) Recursive stack frames (O(1) if iterative)

🔵 Auxiliary Heap

O(1) One new TreeNode allocation

🟢 Output Space

O(1) Root reference

Boundary Best / Worst Cases

Best Case

O(1)O(1)O(1) if inserting into empty root, O(log⁡N)O(\log N)O(logN) on balanced BST.

Average Case

O(log⁡N)O(\log N)O(logN).

Worst Case

O(N)O(N)O(N) on degenerate 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: "insert into a binary search tree". Functional recursive tree splicing: the function returns the root of the modified subtree.

CONSTRAINTS & BOUNDS

N≤104N \le 10^4N≤104, values distinct. Time budget O(H)O(H)O(H) where H≤NH \le NH≤N.

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