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 1372

Longest ZigZag Path in a Binary Tree (LeetCode 1372)

Target Frequency:AmazonGoogleMeta

You're handed a binary tree's root. Starting from any node, walk down while flipping which side you step to at every hop — left, then right, then left, and so on — for as long as the next hop exists; count the edges that walk covers as its length. Report the greatest such length found anywhere in the tree.

Worked Examples

Example 1
Input:root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]
Output:3
11111111
Explanation: The longest ZigZag path goes right, then left, then right: 3 edges.
Example 2
Input:root = [1,1,1,null,1,null,null,1,1,null,1]
Output:4
1111111
Explanation: The longest ZigZag path goes left, right, left, right: 4 edges.
Example 3
Input:root = [1]
Output:0
1
Explanation: A single node has no edges to move along.

⚖️Formal Constraints & Bounds

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

  • 1 <= Node.val <= 100

Deep-Dive & Conceptual Insights

Core Insight

Pass the arrival direction and current run length down. From each node, the child that turns continues the run with length + 1, and the child in the same direction starts a new run of length 1. Both calls always happen, so runs starting at every node are covered in one pass.

Real-World Scenario & Production Applications

Longest alternating decision sequence in a binary decision tree, longest run of alternating left/right moves in a branching route.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Carry the Arrival Direction and Run Length

Each call is told whether it arrived by a left edge and how many alternating edges end at it. Every node is a possible end of a zigzag, so the best is updated on arrival.

Mathematical Recurrence / Code Invariant
if not node:
    return
longest = max(longest, length)
Code Shape
Archetype Code Shape
Python
1if not node:
2 return
3longest = max(longest, length)
4if went_left:
5 dfs(node.right, False, length + 1)
6 dfs(node.left, True, 1)
7else:
8 dfs(node.left, True, length + 1)
9 dfs(node.right, False, 1)
10dfs(root.left, True, 1)
11dfs(root.right, False, 1)

Conceptual Narrative

🧠 Pattern Intuition & Real-World Analogy

Count Good Nodes passes the path's maximum down to each child. ZigZag passes down something smaller but stranger: which way you just came from, and how long your current alternating run is. Each node decides its children's state without ever looking back up.

⚡ The Analogy: A Ski Slalom Where Every Gate Must Switch Sides

A skier runs a slalom course laid out like a tree of gates. A run only counts while each gate is passed on the opposite side from the one before. At every gate the skier knows two things: which side they took the last gate on, and how many alternating gates they have strung together. Switching sides extends the run by one. Taking the same side twice doesn't end the day; it simply starts a fresh run that already counts that one gate.

🔑 The Key Idea in the Code

Every node launches both options at once: the child that continues the zigzag inherits length + 1, and the child that breaks it starts over at 1. Because both calls always happen, zigzags starting at every node in the tree are explored in the same single pass, with no outer loop over starting points.

  • Restarting at 0 instead of 1: Restarting at 0 instead of 1 undercounts every run that starts below the root ([1,2,null,3,null,null,4] has answer 2, but a reset to 0 reports 1).

  • Only following zigzags from the root: Only following zigzags that start at the root misses runs that start deeper.

  • Counting nodes instead of edges: A single node has length 0, because length counts edges, not nodes.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Longest path that alternates left and right, starting at any node, measured in edges.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: length counts the alternating edges ending at this node; turning adds one, repeating a direction resets to 1.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Resetting to 0 instead of 1: the edge that breaks the old run is the first edge of the new one.

  • Only starting from the root: zigzags can begin at any node.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I call dfs(node, went_left, length), which returns on None and updates a global longest. If I arrived by a left edge, the right child continues the zigzag with length + 1 and the left child starts a new one with 1; otherwise it's the mirror image. I seed it with dfs(root.left, True, 1) and dfs(root.right, False, 1). Every node is visited once: O(N) time, O(H) stack.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at dfs(node, went_left, length): each node is reached exactly once, because every node has exactly one incoming edge and each call recurses into each child once. Both the 'continue' and 'restart' runs are handled by those same two calls, so runs starting at every node cost nothing extra: O(1) work per node, O(N) total. Starting a fresh walk from every node instead would cost O(N · H).

SPACE COMPLEXITY

O(H) Auxiliary

Only the recursion stack grows, one frame per level of the current path, so auxiliary space is the tree height H. The direction flag and length are O(1) per frame.

Formal Recurrence Relation

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

Derivation Progression

Top-Down Visit

N node visits

Each node is entered once, through its single parent edge.

O(1) Work Per Frame

max(longest, length); two child calls

One call continues the run with length + 1, the other restarts it at 1.

Total Time

O(N)

N frames with constant work each; no outer loop over starting nodes.

Variable Definitions

NNN

Total number of nodes in the binary 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) global best

🟢 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: "longest ZigZag path", "alternate left and right", "start from any node". Top-down parameter passing with a direction state: each call is told which way it arrived and how long the current alternating run is.

CONSTRAINTS & BOUNDS

N≤5×104N \le 5 \times 10^4N≤5×104. One pass: O(N)O(N)O(N) time.

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

Longest ZigZag Path in a Binary Tree (LeetCode 1372)

Target Frequency:AmazonGoogleMeta

You're handed a binary tree's root. Starting from any node, walk down while flipping which side you step to at every hop — left, then right, then left, and so on — for as long as the next hop exists; count the edges that walk covers as its length. Report the greatest such length found anywhere in the tree.

Worked Examples

Example 1
Input:root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]
Output:3
11111111
Explanation: The longest ZigZag path goes right, then left, then right: 3 edges.
Example 2
Input:root = [1,1,1,null,1,null,null,1,1,null,1]
Output:4
1111111
Explanation: The longest ZigZag path goes left, right, left, right: 4 edges.
Example 3
Input:root = [1]
Output:0
1
Explanation: A single node has no edges to move along.

⚖️Formal Constraints & Bounds

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

  • 1 <= Node.val <= 100

Deep-Dive & Conceptual Insights

Core Insight

Pass the arrival direction and current run length down. From each node, the child that turns continues the run with length + 1, and the child in the same direction starts a new run of length 1. Both calls always happen, so runs starting at every node are covered in one pass.

Real-World Scenario & Production Applications

Longest alternating decision sequence in a binary decision tree, longest run of alternating left/right moves in a branching route.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Carry the Arrival Direction and Run Length

Each call is told whether it arrived by a left edge and how many alternating edges end at it. Every node is a possible end of a zigzag, so the best is updated on arrival.

Mathematical Recurrence / Code Invariant
if not node:
    return
longest = max(longest, length)
Code Shape
Archetype Code Shape
Python
1if not node:
2 return
3longest = max(longest, length)
4if went_left:
5 dfs(node.right, False, length + 1)
6 dfs(node.left, True, 1)
7else:
8 dfs(node.left, True, length + 1)
9 dfs(node.right, False, 1)
10dfs(root.left, True, 1)
11dfs(root.right, False, 1)

Conceptual Narrative

🧠 Pattern Intuition & Real-World Analogy

Count Good Nodes passes the path's maximum down to each child. ZigZag passes down something smaller but stranger: which way you just came from, and how long your current alternating run is. Each node decides its children's state without ever looking back up.

⚡ The Analogy: A Ski Slalom Where Every Gate Must Switch Sides

A skier runs a slalom course laid out like a tree of gates. A run only counts while each gate is passed on the opposite side from the one before. At every gate the skier knows two things: which side they took the last gate on, and how many alternating gates they have strung together. Switching sides extends the run by one. Taking the same side twice doesn't end the day; it simply starts a fresh run that already counts that one gate.

🔑 The Key Idea in the Code

Every node launches both options at once: the child that continues the zigzag inherits length + 1, and the child that breaks it starts over at 1. Because both calls always happen, zigzags starting at every node in the tree are explored in the same single pass, with no outer loop over starting points.

  • Restarting at 0 instead of 1: Restarting at 0 instead of 1 undercounts every run that starts below the root ([1,2,null,3,null,null,4] has answer 2, but a reset to 0 reports 1).

  • Only following zigzags from the root: Only following zigzags that start at the root misses runs that start deeper.

  • Counting nodes instead of edges: A single node has length 0, because length counts edges, not nodes.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Longest path that alternates left and right, starting at any node, measured in edges.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: length counts the alternating edges ending at this node; turning adds one, repeating a direction resets to 1.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Resetting to 0 instead of 1: the edge that breaks the old run is the first edge of the new one.

  • Only starting from the root: zigzags can begin at any node.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I call dfs(node, went_left, length), which returns on None and updates a global longest. If I arrived by a left edge, the right child continues the zigzag with length + 1 and the left child starts a new one with 1; otherwise it's the mirror image. I seed it with dfs(root.left, True, 1) and dfs(root.right, False, 1). Every node is visited once: O(N) time, O(H) stack.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at dfs(node, went_left, length): each node is reached exactly once, because every node has exactly one incoming edge and each call recurses into each child once. Both the 'continue' and 'restart' runs are handled by those same two calls, so runs starting at every node cost nothing extra: O(1) work per node, O(N) total. Starting a fresh walk from every node instead would cost O(N · H).

SPACE COMPLEXITY

O(H) Auxiliary

Only the recursion stack grows, one frame per level of the current path, so auxiliary space is the tree height H. The direction flag and length are O(1) per frame.

Formal Recurrence Relation

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

Derivation Progression

Top-Down Visit

N node visits

Each node is entered once, through its single parent edge.

O(1) Work Per Frame

max(longest, length); two child calls

One call continues the run with length + 1, the other restarts it at 1.

Total Time

O(N)

N frames with constant work each; no outer loop over starting nodes.

Variable Definitions

NNN

Total number of nodes in the binary 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) global best

🟢 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: "longest ZigZag path", "alternate left and right", "start from any node". Top-down parameter passing with a direction state: each call is told which way it arrived and how long the current alternating run is.

CONSTRAINTS & BOUNDS

N≤5×104N \le 5 \times 10^4N≤5×104. One pass: O(N)O(N)O(N) time.

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