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 337

House Robber III (LeetCode 337)

Target Frequency:AmazonGoogleMicrosoft

The houses in a neighbourhood are joined like a binary tree. The only way in is the house at root, and every other house is reached from exactly one house above it, its parent. A node's value is the money inside that house.

A burglar may break into any set of houses on one night, with one rule: if two houses joined by an edge (a parent and its child) are both broken into, the alarm goes off. Return the most money the burglar can take without ever breaking into both ends of an edge.

Worked Examples

Example 1
Input:root = [3,2,3,null,3,null,1]
Output:7
23331
Explanation: Rob the root (3) and the two bottom houses (3 and 1). No two of them are parent and child, and 3 + 3 + 1 = 7.
Example 2
Input:root = [3,4,5,1,3,null,1]
Output:9
143351
Explanation: Skip the root and rob its two children, 4 + 5 = 9. Robbing the root instead leaves only the bottom row, 3 + 1 + 3 + 1 = 8.

⚖️Formal Constraints & Bounds

  • The number of nodes in the tree is in the range [1, 104].

  • 0 <= Node.val <= 104

Deep-Dive & Conceptual Insights

Core Insight

One number per subtree hides whether the child was robbed, so each subtree returns two: the best total with its root robbed and with it skipped. A robbed parent adds its children's skipped totals, a skipped parent adds each child's better total, and the root takes the better of its own two.

Real-World Scenario & Production Applications

Picking people from an org chart so that nobody is picked together with their direct manager, while maximizing a total score, is the same problem: textbooks call it planning a company party. Any hierarchy with a parent-child exclusion rule, such as not scheduling a service and the one it directly depends on in the same maintenance window, has this shape.

Step-by-Step Execution Trace Table

Example 1, root = [3,2,3,null,3,null,1], in postorder (each row is one dfs(node) returning):

Stepnodeleft (rob, skip)right (rob, skip)rob_this = node.val + left_skip + right_skipskip_this = max(left) + max(right)Returns
13, the right child of 2(0, 0)(0, 0)3 + 0 + 0 = 30 + 0 = 0(3, 0)
22(0, 0)(3, 0)2 + 0 + 0 = 20 + 3 = 3(2, 3)
31, the right child of the right 3(0, 0)(0, 0)1 + 0 + 0 = 10 + 0 = 0(1, 0)
43, the right child of the root(0, 0)(1, 0)3 + 0 + 0 = 30 + 1 = 1(3, 1)
53, the root(2, 3)(3, 1)3 + 3 + 1 = 73 + 3 = 6(7, 6)
Endmax(7, 6) = 7

At step 2, taking the right child's best, max(3, 0) = 3, in rob_this would give 2 + 0 + 3 = 5: house 2 robbed together with the 3 below it. Carried up, that mistake makes the root report 12.

Trace Inputroot = [3,2,3,null,3,null,1]
Expected7

Example 1, root = [3,2,3,null,3,null,1], in postorder (each row is one dfs(node) returning):

Stepnodeleft (rob, skip)right (rob, skip)rob_this = node.val + left_skip + right_skipskip_this = max(left) + max(right)Returns
13, the right child of 2(0, 0)(0, 0)3 + 0 + 0 = 30 + 0 = 0(3, 0)
22(0, 0)(3, 0)2 + 0 + 0 = 20 + 3 = 3(2, 3)
31, the right child of the right 3(0, 0)(0, 0)1 + 0 + 0 = 10 + 0 = 0(1, 0)
43, the right child of the root(0, 0)(1, 0)3 + 0 + 0 = 30 + 1 = 1(3, 1)
53, the root(2, 3)(3, 1)3 + 3 + 1 = 73 + 3 = 6(7, 6)
Endmax(7, 6) = 7

At step 2, taking the right child's best, max(3, 0) = 3, in rob_this would give 2 + 0 + 3 = 5: house 2 robbed together with the 3 below it. Carried up, that mistake makes the root report 12.

Code Shape
Archetype Code Shape
Python
1One number per subtree can't tell the parent whether the child was robbed, so `dfs(node)` returns two: `(rob_this, skip_this)`, the best total in `node`'s subtree when `node` is robbed and when it is skipped.
2The parent applies the rule: a robbed node needs both children skipped, a skipped node lets each child take its better state. Answer with `max(dfs(root))`, since the root may be either.
3The shape: `if not node: return (0, 0)`; `left_rob, left_skip = dfs(node.left)`; `right_rob, right_skip = dfs(node.right)`; build `rob_this` and `skip_this`; `return (rob_this, skip_this)`.
4The trap: `rob_this = node.val + left_skip + right_skip`, never `node.val + max(left_rob, left_skip) + ...`: on `[3,2,3,null,3,null,1]` taking the child's max returns 12 instead of 7.

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Bottom-Up DFS lets every subtree hand its parent one finished number. House Robber III breaks that: the best total for a subtree depends on whether its root is robbed, and the parent needs to know which, because a robbed parent can't sit on top of a robbed child. So each subtree hands up one best total per state of its root: (rob_this, skip_this). The parent picks from those states under the rule, and nothing below the children is ever looked at again. That is Tree State DP: the House Robber recurrence of Linear DP, moved onto a tree.

🏢 The Analogy: Two Numbers From Every Team

A company picks staff for a weekend shift, and no one may work it together with their direct manager. Each team lead sends up two numbers: the best total the team can give if the lead works, and if the lead stays home. The lead's own manager never asks for names. If she works, she adds each team's stays-home number; if she stays home, she adds each team's larger number. One number per team would not be enough: she couldn't tell whether it already counts the lead she may not work with.

🔑 Why It Works

Each pair is final when it is returned: rob_this and skip_this both respect the rule everywhere below node. The rule only links a node to its children, so the parent enforces it with the children's states alone. The trap sits on the rob_this line: a child's better state, max(left_rob, left_skip), may be the one where the child is robbed, so a robbed node adds left_skip, never the child's max.

  • Adding max(left_rob, left_skip) to rob_this

  • Adding left_rob + right_rob to skip_this

  • Returning dfs(root)[0] instead of max(dfs(root))

  • Recursing into grandchildren instead of returning both states

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"Binary tree" plus a rule between directly linked nodes ("both ends of an edge") plus "the most money": every node is a yes/no choice, and which choices are allowed depends on the children's choices. That is the signal for Tree State DP: each node returns one best total per state it can be in.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

A robbed node needs both children skipped: rob_this = node.val + left_skip + right_skip. A skipped node lets each child take its better state: skip_this = max(left_rob, left_skip) + max(right_rob, right_skip). The answer is max(dfs(root)).

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • The card's trap: rob_this adds left_skip + right_skip, never a child's better state.

  • Call dfs once per child and unpack the pair (left_rob, left_skip = dfs(node.left)). Reading dfs(node.left)[1] for rob_this and calling dfs(node.left) again for skip_this solves every subtree twice per level: on a chain of 20 houses that is over 4 million calls instead of 41.

  • If you memoize the grandchildren version instead, key the memo by the node itself, never by node.val: different houses can hold the same amount, and a value key hands one house's answer to another.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use Tree State DP. The rule links each house to its parent, so one number per subtree isn't enough: the parent needs to know whether its child was robbed. So my DFS returns two numbers for every node: the best total in its subtree if the node is robbed, and if it is skipped. I compute them in postorder. If I rob the node, both children must be skipped, so rob_this is node.val plus the two children's skip values. If I skip it, each child is free, so skip_this adds the larger of each child's two values. The answer is the larger of the root's two. The trap is robbing a node on top of a child's best total: that best may already rob the child, which breaks the rule. Each node is solved once, so it's O(N) time and O(H) recursion stack.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the code: dfs is called once for every node and once for every empty child slot, and a tree with N nodes has N + 1 empty slots, so there are 2N + 1 calls. Each call does O(1) work: two tuple unpacks, one sum for rob_this, and two max calls and one sum for skip_this. No subtree is solved twice, because each call hands both of its states up and the parent reuses them instead of calling dfs on a grandchild. Total: O(N).

SPACE COMPLEXITY

O(H) recursion stack

The recursion goes down one level per call, so the call stack holds at most H + 1 frames, where H is the height of the tree: about log N when it is balanced, and N on a chain. Each frame keeps four integers. The answer is one integer.

Formal Recurrence Relation

T(N)=(2N+1)⋅O(1)=O(N)T(N) = (2N + 1) \cdot O(1) = O(N)T(N)=(2N+1)⋅O(1)=O(N)

Derivation Progression

Calls

N + (N + 1) = 2N + 1

dfs runs once per node and once per empty child slot, where if not node: return (0, 0) answers at once.

Work per call

O(1)

Unpack left_rob, left_skip and right_rob, right_skip, add up rob_this, take two max values for skip_this, return the pair.

No repeated subtrees

each subtree solved once

The parent reuses the pair its child returned; it never calls dfs on a grandchild, which is what makes the brute force exponential.

Total

O(N)

2N + 1 calls, O(1) each, then one max at the root.

Variable Definitions

NNN

Number of nodes (houses) in the tree

HHH

Height of the tree: about log N when balanced, up to N on a chain

Memory Architecture & Bounds

🟣 Call Stack

O(H): one frame per level of the current root-to-node path

🔵 Auxiliary Heap

O(1): each frame keeps four integers, no extra structure

🟢 Output Space

O(1): one integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N) time and an O(log⁡N)O(\log N)O(logN) stack on a balanced tree

Average Case

O(N)O(N)O(N) time; the stack depth is the tree height

Worst Case

O(N)O(N)O(N) time and an O(N)O(N)O(N) stack on a chain

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: "binary tree", "both ends of an edge", "the most money". A yes/no choice at every node plus a rule between a parent and its child: Tree State DP, where each node returns one best total per state it can be in.

CONSTRAINTS & BOUNDS

1≤N≤1041 \le N \le 10^41≤N≤104 nodes and values up to 10410^4104, so any total stays below 10810^8108. Trying every set of houses is 2N2^N2N; recursing on grandchildren without saving results is exponential in the height; returning both states is O(N)O(N)O(N) time and an O(H)O(H)O(H) recursion stack.

FAANG PRODUCTION TRAPS & EDGE CASES

A chain of 10410^4104 houses is 10410^4104 calls deep, past the default recursion limit of many runtimes (CPython's is 1000): raise the limit or run the same postorder with an explicit stack. Memoizing rob(node) in a hash map keyed by node also reaches O(N)O(N)O(N), but pays for an extra map of NNN entries; returning the pair needs no map at all.

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

House Robber III (LeetCode 337)

Target Frequency:AmazonGoogleMicrosoft

The houses in a neighbourhood are joined like a binary tree. The only way in is the house at root, and every other house is reached from exactly one house above it, its parent. A node's value is the money inside that house.

A burglar may break into any set of houses on one night, with one rule: if two houses joined by an edge (a parent and its child) are both broken into, the alarm goes off. Return the most money the burglar can take without ever breaking into both ends of an edge.

Worked Examples

Example 1
Input:root = [3,2,3,null,3,null,1]
Output:7
23331
Explanation: Rob the root (3) and the two bottom houses (3 and 1). No two of them are parent and child, and 3 + 3 + 1 = 7.
Example 2
Input:root = [3,4,5,1,3,null,1]
Output:9
143351
Explanation: Skip the root and rob its two children, 4 + 5 = 9. Robbing the root instead leaves only the bottom row, 3 + 1 + 3 + 1 = 8.

⚖️Formal Constraints & Bounds

  • The number of nodes in the tree is in the range [1, 104].

  • 0 <= Node.val <= 104

Deep-Dive & Conceptual Insights

Core Insight

One number per subtree hides whether the child was robbed, so each subtree returns two: the best total with its root robbed and with it skipped. A robbed parent adds its children's skipped totals, a skipped parent adds each child's better total, and the root takes the better of its own two.

Real-World Scenario & Production Applications

Picking people from an org chart so that nobody is picked together with their direct manager, while maximizing a total score, is the same problem: textbooks call it planning a company party. Any hierarchy with a parent-child exclusion rule, such as not scheduling a service and the one it directly depends on in the same maintenance window, has this shape.

Step-by-Step Execution Trace Table

Example 1, root = [3,2,3,null,3,null,1], in postorder (each row is one dfs(node) returning):

Stepnodeleft (rob, skip)right (rob, skip)rob_this = node.val + left_skip + right_skipskip_this = max(left) + max(right)Returns
13, the right child of 2(0, 0)(0, 0)3 + 0 + 0 = 30 + 0 = 0(3, 0)
22(0, 0)(3, 0)2 + 0 + 0 = 20 + 3 = 3(2, 3)
31, the right child of the right 3(0, 0)(0, 0)1 + 0 + 0 = 10 + 0 = 0(1, 0)
43, the right child of the root(0, 0)(1, 0)3 + 0 + 0 = 30 + 1 = 1(3, 1)
53, the root(2, 3)(3, 1)3 + 3 + 1 = 73 + 3 = 6(7, 6)
Endmax(7, 6) = 7

At step 2, taking the right child's best, max(3, 0) = 3, in rob_this would give 2 + 0 + 3 = 5: house 2 robbed together with the 3 below it. Carried up, that mistake makes the root report 12.

Trace Inputroot = [3,2,3,null,3,null,1]
Expected7

Example 1, root = [3,2,3,null,3,null,1], in postorder (each row is one dfs(node) returning):

Stepnodeleft (rob, skip)right (rob, skip)rob_this = node.val + left_skip + right_skipskip_this = max(left) + max(right)Returns
13, the right child of 2(0, 0)(0, 0)3 + 0 + 0 = 30 + 0 = 0(3, 0)
22(0, 0)(3, 0)2 + 0 + 0 = 20 + 3 = 3(2, 3)
31, the right child of the right 3(0, 0)(0, 0)1 + 0 + 0 = 10 + 0 = 0(1, 0)
43, the right child of the root(0, 0)(1, 0)3 + 0 + 0 = 30 + 1 = 1(3, 1)
53, the root(2, 3)(3, 1)3 + 3 + 1 = 73 + 3 = 6(7, 6)
Endmax(7, 6) = 7

At step 2, taking the right child's best, max(3, 0) = 3, in rob_this would give 2 + 0 + 3 = 5: house 2 robbed together with the 3 below it. Carried up, that mistake makes the root report 12.

Code Shape
Archetype Code Shape
Python
1One number per subtree can't tell the parent whether the child was robbed, so `dfs(node)` returns two: `(rob_this, skip_this)`, the best total in `node`'s subtree when `node` is robbed and when it is skipped.
2The parent applies the rule: a robbed node needs both children skipped, a skipped node lets each child take its better state. Answer with `max(dfs(root))`, since the root may be either.
3The shape: `if not node: return (0, 0)`; `left_rob, left_skip = dfs(node.left)`; `right_rob, right_skip = dfs(node.right)`; build `rob_this` and `skip_this`; `return (rob_this, skip_this)`.
4The trap: `rob_this = node.val + left_skip + right_skip`, never `node.val + max(left_rob, left_skip) + ...`: on `[3,2,3,null,3,null,1]` taking the child's max returns 12 instead of 7.

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Bottom-Up DFS lets every subtree hand its parent one finished number. House Robber III breaks that: the best total for a subtree depends on whether its root is robbed, and the parent needs to know which, because a robbed parent can't sit on top of a robbed child. So each subtree hands up one best total per state of its root: (rob_this, skip_this). The parent picks from those states under the rule, and nothing below the children is ever looked at again. That is Tree State DP: the House Robber recurrence of Linear DP, moved onto a tree.

🏢 The Analogy: Two Numbers From Every Team

A company picks staff for a weekend shift, and no one may work it together with their direct manager. Each team lead sends up two numbers: the best total the team can give if the lead works, and if the lead stays home. The lead's own manager never asks for names. If she works, she adds each team's stays-home number; if she stays home, she adds each team's larger number. One number per team would not be enough: she couldn't tell whether it already counts the lead she may not work with.

🔑 Why It Works

Each pair is final when it is returned: rob_this and skip_this both respect the rule everywhere below node. The rule only links a node to its children, so the parent enforces it with the children's states alone. The trap sits on the rob_this line: a child's better state, max(left_rob, left_skip), may be the one where the child is robbed, so a robbed node adds left_skip, never the child's max.

  • Adding max(left_rob, left_skip) to rob_this

  • Adding left_rob + right_rob to skip_this

  • Returning dfs(root)[0] instead of max(dfs(root))

  • Recursing into grandchildren instead of returning both states

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"Binary tree" plus a rule between directly linked nodes ("both ends of an edge") plus "the most money": every node is a yes/no choice, and which choices are allowed depends on the children's choices. That is the signal for Tree State DP: each node returns one best total per state it can be in.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

A robbed node needs both children skipped: rob_this = node.val + left_skip + right_skip. A skipped node lets each child take its better state: skip_this = max(left_rob, left_skip) + max(right_rob, right_skip). The answer is max(dfs(root)).

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • The card's trap: rob_this adds left_skip + right_skip, never a child's better state.

  • Call dfs once per child and unpack the pair (left_rob, left_skip = dfs(node.left)). Reading dfs(node.left)[1] for rob_this and calling dfs(node.left) again for skip_this solves every subtree twice per level: on a chain of 20 houses that is over 4 million calls instead of 41.

  • If you memoize the grandchildren version instead, key the memo by the node itself, never by node.val: different houses can hold the same amount, and a value key hands one house's answer to another.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use Tree State DP. The rule links each house to its parent, so one number per subtree isn't enough: the parent needs to know whether its child was robbed. So my DFS returns two numbers for every node: the best total in its subtree if the node is robbed, and if it is skipped. I compute them in postorder. If I rob the node, both children must be skipped, so rob_this is node.val plus the two children's skip values. If I skip it, each child is free, so skip_this adds the larger of each child's two values. The answer is the larger of the root's two. The trap is robbing a node on top of a child's best total: that best may already rob the child, which breaks the rule. Each node is solved once, so it's O(N) time and O(H) recursion stack.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the code: dfs is called once for every node and once for every empty child slot, and a tree with N nodes has N + 1 empty slots, so there are 2N + 1 calls. Each call does O(1) work: two tuple unpacks, one sum for rob_this, and two max calls and one sum for skip_this. No subtree is solved twice, because each call hands both of its states up and the parent reuses them instead of calling dfs on a grandchild. Total: O(N).

SPACE COMPLEXITY

O(H) recursion stack

The recursion goes down one level per call, so the call stack holds at most H + 1 frames, where H is the height of the tree: about log N when it is balanced, and N on a chain. Each frame keeps four integers. The answer is one integer.

Formal Recurrence Relation

T(N)=(2N+1)⋅O(1)=O(N)T(N) = (2N + 1) \cdot O(1) = O(N)T(N)=(2N+1)⋅O(1)=O(N)

Derivation Progression

Calls

N + (N + 1) = 2N + 1

dfs runs once per node and once per empty child slot, where if not node: return (0, 0) answers at once.

Work per call

O(1)

Unpack left_rob, left_skip and right_rob, right_skip, add up rob_this, take two max values for skip_this, return the pair.

No repeated subtrees

each subtree solved once

The parent reuses the pair its child returned; it never calls dfs on a grandchild, which is what makes the brute force exponential.

Total

O(N)

2N + 1 calls, O(1) each, then one max at the root.

Variable Definitions

NNN

Number of nodes (houses) in the tree

HHH

Height of the tree: about log N when balanced, up to N on a chain

Memory Architecture & Bounds

🟣 Call Stack

O(H): one frame per level of the current root-to-node path

🔵 Auxiliary Heap

O(1): each frame keeps four integers, no extra structure

🟢 Output Space

O(1): one integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N) time and an O(log⁡N)O(\log N)O(logN) stack on a balanced tree

Average Case

O(N)O(N)O(N) time; the stack depth is the tree height

Worst Case

O(N)O(N)O(N) time and an O(N)O(N)O(N) stack on a chain

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: "binary tree", "both ends of an edge", "the most money". A yes/no choice at every node plus a rule between a parent and its child: Tree State DP, where each node returns one best total per state it can be in.

CONSTRAINTS & BOUNDS

1≤N≤1041 \le N \le 10^41≤N≤104 nodes and values up to 10410^4104, so any total stays below 10810^8108. Trying every set of houses is 2N2^N2N; recursing on grandchildren without saving results is exponential in the height; returning both states is O(N)O(N)O(N) time and an O(H)O(H)O(H) recursion stack.

FAANG PRODUCTION TRAPS & EDGE CASES

A chain of 10410^4104 houses is 10410^4104 calls deep, past the default recursion limit of many runtimes (CPython's is 1000): raise the limit or run the same postorder with an explicit stack. Memoizing rob(node) in a hash map keyed by node also reaches O(N)O(N)O(N), but pays for an extra map of NNN entries; returning the pair needs no map at all.

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