Ryan Peterman
First-principles reasoning and structural invariants allow candidates to reconstruct optimal solutions to complex coding problems without relying on rote memorization.
AI-assisted summary of Testing Neetcode With 3 Leetcode Hards (Live Whiteboarding) — original source. Check the original for full context.
Source published:
Key ideas
- Put on the spot with three random LeetCode Hard problems without preparation, NeetCode demonstrates how deriving solutions from first principles and core algorithmic patterns matters more than rote memorization—even on problems he has not touched in five years. (0:00)
- For Edit Distance (LeetCode #72), framing the problem first as a three-way recursive decision tree (insert, delete, replace) directly yields an O(n × m) time and space 2D dynamic programming table where each cell represents prefix subproblems. (0:00)
- In Median of Two Sorted Arrays (LeetCode #4), because the combined length of the two arrays is fixed, binary searching a partition cut in one array automatically determines the complementary partition boundary in the second array. (5:16)
- Solving N-Queens II (LeetCode #52) relies on an exponential backtracking search optimized with four hash sets that provide O(1) conflict checks across rows, columns, anti-diagonals (row + col), and main diagonals (row - col). (12:05)
Detailed notes
## Background Published by Ryan Peterman on YouTube on October 5, 2026, this video features an unscripted whiteboarding challenge with popular programming educator NeetCode. The session is an excerpt from a longer interview where Peterman tests NeetCode's cold algorithmic problem-solving abilities by presenting him with three random LeetCode Hard questions.
## TL;DR In this whiteboarding demonstration, NeetCode works through three classic LeetCode Hard problems without advance preparation: Edit Distance (#72), Median of Two Sorted Arrays (#4), and N-Queens II (#52). For Edit Distance, he derives the recursive decision tree for string transformations and maps it into a 2D dynamic programming grid. On Median of Two Sorted Arrays, he relies on first principles to reason through binary search partitions across two sorted sets to achieve optimal complexity. Finally, for N-Queens II, he sketches out an efficient backtracking strategy, demonstrating how to track conflicting rows, columns, and diagonal lines in constant time using coordinate sums and differences.
## Atmosphere & style The session feels remarkably candid, relaxed, and authentic, playing out like an informal peer-to-peer technical interview between software engineers. NeetCode approaches each problem with self-deprecating humor and honesty, openly laughing when he forgets specific formulas or admits how tricky partition boundary edge cases can be. Peterman provides encouraging, grounded nudges that keep the pace moving naturally. Watching it feels reassuring and demystifying, illustrating that even top algorithm educators solve hard problems iteratively through fundamental reasoning and visual sketches rather than flawless rote memorization.
## Bulletin - [00:00](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=0s) Put on the spot with three random LeetCode Hard problems without preparation, NeetCode demonstrates how deriving solutions from first principles and core algorithmic patterns matters more than rote memorization—even on problems he has not touched in five years. - [00:00](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=0s) For Edit Distance (LeetCode #72), framing the problem first as a three-way recursive decision tree (insert, delete, replace) directly yields an O(n × m) time and space 2D dynamic programming table where each cell represents prefix subproblems. - [05:16](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=316s) In Median of Two Sorted Arrays (LeetCode #4), because the combined length of the two arrays is fixed, binary searching a partition cut in one array automatically determines the complementary partition boundary in the second array. - [12:05](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=725s) Solving N-Queens II (LeetCode #52) relies on an exponential backtracking search optimized with four hash sets that provide O(1) conflict checks across rows, columns, anti-diagonals (row + col), and main diagonals (row - col).
## Key takeaways - [00:00](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=0s) Because Edit Distance (LeetCode #72) allows character insertion, deletion, and replacement, any arbitrary string can always be transformed into another regardless of initial length differences. - [00:00](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=0s) When comparing characters in Edit Distance, matching characters advance both pointers at zero cost, whereas mismatched characters require branching across all three edit operations because a greedy choice cannot predict future alignments. - [00:00](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=0s) Caching overlapping subproblems in the Edit Distance decision tree leads to an O(n × m) time and space 2D dynamic programming grid where each cell computes the minimum cost of adjacent insert, delete, and replace transitions plus one. - [00:00](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=0s) In live interviews, transitioning to code early when building 2D dynamic programming solutions helps clarify index transitions and boundary edge cases better than trying to hold the entire grid state mentally. - [05:16](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=316s) When tackling Median of Two Sorted Arrays (LeetCode #4) from first principles, drafting a concrete numerical example helps navigate common pitfalls like overlapping intervals, unequal array lengths, and duplicate values. - [05:16](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=316s) Finding the median of two sorted arrays differs based on parity: an odd combined size targets a single middle element, while an even combined size requires averaging two middle numbers and handling extra off-by-one boundary cases. - [05:16](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=316s) Because the total number of elements is fixed in Median of Two Sorted Arrays, performing binary search on a partition boundary in one array automatically dictates where the partition cut must land in the second array. - [05:16](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=316s) Working from first principles and visual intuition allows a candidate to recover complex binary search partitioning logic even five years after last studying the problem. - [10:05](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=605s) Sketching out an n × n visual grid is essential in N-Queens II (LeetCode #52) to spot spatial patterns and design efficient bookkeeping for queen attack paths. - [11:04](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=664s) While tracking occupied rows and columns in N-Queens II only requires simple hash sets of indices, tracking diagonals efficiently requires a coordinate invariant trick. - [12:05](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=725s) Along any anti-diagonal, incrementing the row while decrementing the column keeps the sum (row + col) constant; along any main diagonal, incrementing both coordinates simultaneously keeps the difference (row - col) constant. - [14:41](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=881s) Maintaining four hash sets (rows, columns, positive diagonals, and negative diagonals) enables O(1) validity checks at each square to prune invalid branches immediately within an exponential backtracking search space.
## Detailed walkthrough ### [00:00](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=0s) Tackling Edit Distance (LeetCode #72)
Ryan opens the session by throwing a classic LeetCode Hard problem at NeetCode: Edit Distance. Given two strings, `word1` and `word2`, the objective is to return the minimum number of operations required to transform `word1` into `word2`. The permissible operations are inserting a character, deleting a character, or replacing a character. NeetCode immediately recognizes the problem type, noting that while he does not recall all the fine-grained implementation details off the top of his head, he knows the core algorithmic pattern: formulating a recursive decision tree and caching overlapping subproblems to yield a dynamic programming (DP) solution. Because insertion, deletion, and replacement are allowed, any arbitrary string can unconditionally be transformed into another, regardless of differences in initial string lengths.
NeetCode begins tracing out the decision tree using pointers across the two words. When the characters at the current pointers match, no edit cost is incurred, and the pointers simply advance forward. However, when the characters differ, the algorithm cannot "predict the future" greedily, requiring a brute-force branching across all three edit options: 1. Deleting a character from `word1` 2. Inserting a character into `word1` 3. Replacing (modifying) the character in `word1` to match `word2`
```mermaid flowchart TD accTitle: Edit Distance Decision Tree accDescr: Branching logic when comparing characters in word1 and word2 during edit distance calculation.
Start["Compare word1[i] and word2[j]"] --> Match{"Do characters match?"} Match -->|"Yes: word1[i] == word2[j]"| Advance["Advance both pointers (i+1, j+1)<br/>Cost = 0"] Match -->|"No: word1[i]!= word2[j]"| Branch["Branch 3 Operations<br/>Cost = 1 + min(...)"]
Branch --> OpInsert["Insert character<br/>(i, j+1)"] Branch --> OpDelete["Delete character<br/>(i+1, j)"] Branch --> OpReplace["Replace character<br/>(i+1, j+1)"] ```
From this recursive formulation, NeetCode outlines the transition into a 2D bottom-up dynamic programming table of size $O(n \times m)$ time and space complexity, where $n$ and $m$ are the lengths of the respective strings. When Ryan asks what an individual cell in that grid represents, NeetCode laughs, acknowledging that indexing DP tables is often where people get tripped up. He explains that each cell corresponds to the subproblem answer for the prefixes (or substrings) up to indices $i$ and $j$. To compute the value of any given cell, the algorithm looks back at adjacent neighboring cells representing the insert, delete, and replace transitions, taking the minimum cost among them plus one. NeetCode notes that in a real interview setting, he typically starts writing code at this stage because working directly with indices in code helps clarify edge cases and directional transitions better than trying to hold the entire grid state in his head. Ryan confirms NeetCode is on the right track, acknowledging that completing it is simply a matter of careful case analysis.
[05:16](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=316s) Median of Two Sorted Arrays (LeetCode #4)
Ryan shifts to a notoriously tricky binary search problem: finding the median of two sorted arrays. NeetCode admits that this problem is "always annoying" and begins drafting a concrete numerical example with nine total elements across two arrays to derive the intuition from first principles. He points out common interview pitfalls, such as overlapping intervals, unequal lengths, and duplicate values between the arrays. NeetCode reflects on interview time management: while he could take the time to align all elements sequentially and even color-code them to visualize the partitions, he knows the optimal target complexity requires some flavor of binary search, so his primary focus is deducing the partitioning trick.
He attempts to eliminate sections of the arrays using two pointers (`left` and `right`) in both arrays simultaneously, laughing when he admits, "I don't remember how to do that." Ryan briefly mentions a target before immediately clarifying that the problem strictly seeks the median, which NeetCode notes actually constrains the search space favorably: - For an odd combined size (e.g., $9$ elements), the goal is to pinpoint the exact $5^{\text{th}}$ element overall. - For an even combined size, the median requires averaging the two middle numbers, introducing additional off-by-one boundary cases.
NeetCode reasons that because the total length is fixed, one does not need to perform an independent binary search across both arrays; instead, performing binary search on a partition boundary in one array automatically dictates where the corresponding partition cut must land in the second array. By comparing the medians or boundary elements of both partitions, one can determine whether the combined partition is shifted too far to the left or too far to the right. NeetCode jokes that wrestling with these partition boundary edge cases is the moment in an interview where he would need to grab a cup of coffee. He remarks that it has been five years since he originally made his YouTube explanation video for the problem and had not touched it since, but emphasizes that working from first principles allows a candidate to get remarkably close to the right intuition even without rote memorization.
[10:05](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=605s) Introducing N-Queens II (LeetCode #52)
Ryan raises the stakes with another Hard problem: N-Queens II. Given an $n \times n$ chessboard, the task is to return the total number of distinct board configurations where $n$ queens can be placed such that no two queens attack each other. Ryan recaps the standard chess rules for queens: they can attack any piece sharing the same row, column, or diagonal. NeetCode immediately starts sketching out an $n \times n$ grid, observing that visual layout is essential for spotting the underlying spatial patterns and bookkeeping tricks needed to track conflicting columns and diagonals efficiently.
[11:04](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=664s) Formulating the Backtracking Strategy and the Diagonal Challenge
NeetCode begins breaking down LeetCode #52 (N-Queens II) from memory, asking himself how to systematically prevent queens from attacking one another. He identifies that a trial-and-error backtracking algorithm is the best and most standard approach. Checking for shared rows and columns is straightforward: one can simply maintain hash sets for rows and columns to track occupied lines.
The crux of the problem lies in efficiently tracking the diagonals. Unlike rows and columns, there is no direct coordinate label for a diagonal line on a grid. Addressing the common viewer question of "how would you know this?", NeetCode candidly admits that it relies on a specific mathematical trick that he certainly did not invent himself, but remembers as the standard way to model diagonals cleanly.
```mermaid flowchart TD accTitle: N-Queens Board Conflict Tracking accDescr: Tracking queen attacks across rows, columns, positive diagonals, and negative diagonals using coordinate formulas. subgraph Constraints["Coordinate Invariants for Attacks"] R["Row: r"] C["Column: c"] D1["Anti-Diagonal: r + c"] D2["Main Diagonal: r - c"] end subgraph StateSets["Hash Sets for O(1) Lookup"] SR["rows = set()"] SC["cols = set()"] SD1["pos_diag = set()"] SD2["neg_diag = set()"] end R --> SR C --> SC D1 --> SD1 D2 --> SD2 ```
[12:05](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=725s) Deriving the Diagonal Invariants: Sums and Differences
To explain the diagonal invariant, NeetCode visualizes placing a queen on a square such as row 1, column 1. Moving along one diagonal direction increments the row index by 1 while decrementing the column index by 1 (or vice versa). Because one coordinate increases by the exact amount the other decreases, their sum remains perfectly constant along that entire anti-diagonal line (e.g., $1 + 1 = 2$). Thus, `row + col` serves as a unique identifier for that diagonal.
When it comes to the opposing diagonal, NeetCode pauses for a moment, admitting with a small laugh that he does not instantly remember the exact formula off the top of his head. Ryan Peterman clarifies the objective: NeetCode is simply trying to achieve rapid $O(1)$ diagonal membership checks to determine whether a given diagonal is already under attack. NeetCode walks through the coordinates along that line—$(0, 0)$, $(1, 1)$, $(2, 2)$—and notices that both indices grow simultaneously. He concludes that taking the difference rather than the sum keeps the value constant: - For anti-diagonals (slanted one way), the sum `row + col` remains identical. - For main diagonals (slanted the other way), the difference `row - col` remains identical.
[14:41](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=881s) Decision Tree, Backtracking Execution, and Time Complexity
With four hash data structures established (rows, columns, positive diagonals, and negative diagonals), the backtracking procedure iterates through board positions. At each candidate square, the algorithm checks whether placing a queen violates any of the four hash sets. If the square is free from attacks, the queen is placed, the sets are updated, and the search recurses deeper; otherwise, the square is skipped, pruning invalid paths immediately. Ryan Peterman summarizes the approach as a brute-force search augmented with constant-time validity checks before each step forward.
When discussing the runtime complexity, NeetCode notes that while each hash set lookup is $O(1)$, the overall recursion tree grows substantially. While he does not give an exact closed-form bound off the top of his head—mentioning it could be roughly exponential or on the order of $N^N$—it represents the optimal backtracking solution for the problem. Ryan agrees that the design is completely sound, wrapping up the challenge.
- **Data structures used**: Four hash sets to track occupied rows, columns, anti-diagonals (`r + c`), and main diagonals (`r - c`). - **Pruning mechanism**: Skip squares where coordinates already exist in any of the four sets. - **Complexity intuition**: $O(1)$ membership checks per placement decision, operating over an exponential backtracking search space.
## Notable quotes > [05:16](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=316s) I don't remember how to do that. — NeetCode
> [11:04](https://www.youtube.com/watch?v=rbtO3a6Qb00&t=664s) how would you know this? — NeetCode
## Mentioned Ryan Peterman, NeetCode, YouTube, LeetCode, LeetCode #72: Edit Distance, LeetCode #4: Median of Two Sorted Arrays, LeetCode #52: N-Queens II
## Video description During the full interview we did here: https://youtu.be/K15dND_Kfvg
I was curious how good he was at Leetcode without any preparation. Here's a little rough cut of me asking him three random Leetcode hard questions and seeing what he came up with
0:00 — LeetCode #72: Edit Distance https://leetcode.com/problems/edit-distance/
5:16 — LeetCode #4: Median of Two Sorted Arrays https://leetcode.com/problems/median-of-two-sorted-arrays/
10:05 — LeetCode #52: N-Queens II https://leetcode.com/problems/n-queens-ii/
[Source](https://www.youtube.com/watch?v=rbtO3a6Qb00)