KnowledgeWala • Top 50 LeetCode Series • Part 5 of 10 • 5 Problems • ~40 min • 8 min per problem

Top 50 LeetCode — Part 5
Problems 21–25

Problems in this part: 21. Linked List Cycle EASY, 22. Remove Nth Node From End MEDIUM, 23. Reorder List MEDIUM, 24. Add Two Numbers MEDIUM, 25. Maximum Depth of Binary Tree EASY

Part 1 Part 2 Part 3 Part 4 Part 5 • You are here Part 6 Part 7 Part 8 Part 9 Part 10

How to read each problem: Program → Explanation in details → Solution Logic → Code → Code Explanation. Complete runnable code, verified. Every code block now has 📋 Copy Code button + line-by-line comments + Expected Output — paste in IDE and run. Type it, run it, then say the logic aloud in 60 seconds.

Series rule: Not short, not 50 in one post. 5 problems per post, deeply explained, beautifully structured — linked as a series.

Problem 21 of 50 • Fast/Slow • LC 141

21. Linked List Cycle EASY

Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation

🧩 Program / Problem: Detect cycle in linked list.

STEP 1 Explanation in Details — Why This Works

Floyd: slow 1, fast 2. If cycle, fast laps slow.

STEP 2 Solution Logic — Step by Step

slow=head,fast=head. While fast and fast.next: slow++, fast+=2, if equal true. Return false.

STEP 3 Code — Complete & Runnable in Java

✅ Complete file — copy into one .java file named after the class, run it. Includes import, class, solution method, main() with test, and helper classes (ListNode / TreeNode / Node) where needed.

// ALGORITHM - READ BEFORE CODE:
// 1. Understand input/output from Expected Output below.
// 2. Think brute force first, then optimise (see STEP 1-2 in explanation).
// 3. Dry-run with the sample input on paper - trace each variable.
// 4. Then run this code - if output matches Expected Output, logic is correct.
// COPY-PASTE READY - Paste in LeetCode / IntelliJ / VS Code and Run
// How to run: Create Solution.java, paste this file, run main() below.
// Read the comments - each block explains WHY, not just WHAT.
public class LinkedListCycle {
    static class ListNode { int val; ListNode next; ListNode(int v){val=v;} }
    public boolean hasCycle(ListNode head) {
        ListNode slow = head, fast = head;
        // WHY: Keep going while condition holds - shrink / expand window or move pointers.
        while (fast != null && fast.next != null) {
            slow = slow.next; fast = fast.next.next;
            // WHY: Check the key condition - if true, we found the answer / edge case.
            if (slow == fast) return true;
        }
        // WHY: Return here - we found the answer, no need to check more.
        return false;
    }
    public static void main(String[] args) {
        // WHY: Create the helper structure - it trades a little memory for a lot of speed.
        ListNode h = new ListNode(3); h.next = new ListNode(2); h.next.next = new ListNode(0); h.next.next.next = new ListNode(-4);
        h.next.next.next.next = h.next; // cycle
        // WHY: Create the helper structure - it trades a little memory for a lot of speed.
        System.out.println(new LinkedListCycle().hasCycle(h)); // true
    }
}
// EXPECTED OUTPUT for sample above:
// Input: head = [3,2,0,-4], pos = 1
// Output: true  // cycle at node 2
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
▶ Try It Yourself — Expected Output
Input: head = [3,2,0,-4], pos = 1
Output: true // cycle at node 2
Copy the code above → paste in your IDE → run main() → compare your output with this. If it matches, move to the next problem.

STEP 4 Code Explanation — Line by Line

In cycle distance shrinks by 1 each step, must meet. Time O(n), Space O(1).

🗣 How to say it in interview: First state brute force + its cost, then say “I will trade memory for time” (or “use two pointers / DP”), walk one dry-run example, then write code. Close with Time + Space + edge cases.
Problem 22 of 50 • Two Pointers • LC 19

22. Remove Nth Node From End MEDIUM

Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation

🧩 Program / Problem: Remove nth from end in one pass.

STEP 1 Explanation in Details — Why This Works

Fast moves n+1 ahead (with dummy). Then both move. Slow ends before target.

STEP 2 Solution Logic — Step by Step

Dummy->head. fast=dummy. Move fast n+1. Move both to end. slow.next=slow.next.next.

STEP 3 Code — Complete & Runnable in Java

✅ Complete file — copy into one .java file named after the class, run it. Includes import, class, solution method, main() with test, and helper classes (ListNode / TreeNode / Node) where needed.

// ALGORITHM - READ BEFORE CODE:
// 1. Understand input/output from Expected Output below.
// 2. Think brute force first, then optimise (see STEP 1-2 in explanation).
// 3. Dry-run with the sample input on paper - trace each variable.
// 4. Then run this code - if output matches Expected Output, logic is correct.
// COPY-PASTE READY - Paste in LeetCode / IntelliJ / VS Code and Run
// How to run: Create Solution.java, paste this file, run main() below.
// Read the comments - each block explains WHY, not just WHAT.
public class RemoveNthFromEnd {
    static class ListNode { int val; ListNode next; ListNode(int v){val=v;} }
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // WHY: Create the helper structure - it trades a little memory for a lot of speed.
        ListNode dummy = new ListNode(0); dummy.next = head;
        ListNode fast = dummy, slow = dummy;
        // WHY: Loop through every element once - we check each one exactly once, O(n).
        for (int i = 0; i <= n; i++) fast = fast.next;
        // WHY: Keep going while condition holds - shrink / expand window or move pointers.
        while (fast != null) { fast = fast.next; slow = slow.next; }
        slow.next = slow.next.next;
        // WHY: Return here - we found the answer, no need to check more.
        return dummy.next;
    }
    static void print(ListNode h){ while(h!=null){ System.out.print(h.val+" "); h=h.next; } System.out.println(); }
    public static void main(String[] args) {
        // WHY: Create the helper structure - it trades a little memory for a lot of speed.
        ListNode h = new ListNode(1); h.next = new ListNode(2); h.next.next = new ListNode(3); h.next.next.next = new ListNode(4); h.next.next.next.next = new ListNode(5);
        print(new RemoveNthFromEnd().removeNthFromEnd(h, 2)); // 1 2 3 5
    }
}
// EXPECTED OUTPUT for sample above:
// Input: head = [1,2,3,4,5], n = 2
// Output: [1,2,3,5]  // removed 4
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
▶ Try It Yourself — Expected Output
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5] // removed 4
Copy the code above → paste in your IDE → run main() → compare your output with this. If it matches, move to the next problem.

STEP 4 Code Explanation — Line by Line

Dummy handles removing head. One pass O(n).

🗣 How to say it in interview: First state brute force + its cost, then say “I will trade memory for time” (or “use two pointers / DP”), walk one dry-run example, then write code. Close with Time + Space + edge cases.
Problem 23 of 50 • List + Reverse • LC 143

23. Reorder List MEDIUM

Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation

🧩 Program / Problem: Reorder L0->Ln->L1->Ln-1...

STEP 1 Explanation in Details — Why This Works

Find middle, reverse second half, merge alternating.

STEP 2 Solution Logic — Step by Step

Middle via slow/fast. Reverse second. Merge one from first, one from reversed.

STEP 3 Code — Complete & Runnable in Java

✅ Complete file — copy into one .java file named after the class, run it. Includes import, class, solution method, main() with test, and helper classes (ListNode / TreeNode / Node) where needed.

// ALGORITHM - READ BEFORE CODE:
// 1. Understand input/output from Expected Output below.
// 2. Think brute force first, then optimise (see STEP 1-2 in explanation).
// 3. Dry-run with the sample input on paper - trace each variable.
// 4. Then run this code - if output matches Expected Output, logic is correct.
// COPY-PASTE READY - Paste in LeetCode / IntelliJ / VS Code and Run
// How to run: Create Solution.java, paste this file, run main() below.
// Read the comments - each block explains WHY, not just WHAT.
public class ReorderList {
    static class ListNode { int val; ListNode next; ListNode(int v){val=v;} }
    public void reorderList(ListNode head) {
        // WHY: Check the key condition - if true, we found the answer / edge case.
        if (head == null) return;
        ListNode slow = head, fast = head;
        // WHY: Keep going while condition holds - shrink / expand window or move pointers.
        while (fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; }
        ListNode second = reverse(slow.next); slow.next = null;
        ListNode first = head;
        // WHY: Keep going while condition holds - shrink / expand window or move pointers.
        while (second != null) {
            ListNode t1 = first.next, t2 = second.next;
            first.next = second; second.next = t1; first = t1; second = t2;
        }
    }
    ListNode reverse(ListNode h) { ListNode p = null; while (h != null) { ListNode n = h.next; h.next = p; p = h; h = n; } return p; }
    static void print(ListNode h){ while(h!=null){ System.out.print(h.val+" "); h=h.next; } System.out.println(); }
    public static void main(String[] args) {
        // WHY: Create the helper structure - it trades a little memory for a lot of speed.
        ListNode h = new ListNode(1); h.next = new ListNode(2); h.next.next = new ListNode(3); h.next.next.next = new ListNode(4);
        // WHY: Create the helper structure - it trades a little memory for a lot of speed.
        new ReorderList().reorderList(h); print(h); // 1 4 2 3
    }
}
// EXPECTED OUTPUT for sample above:
// Input: head = [1,2,3,4]
// Output: [1,4,2,3]
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
▶ Try It Yourself — Expected Output
Input: head = [1,2,3,4]
Output: [1,4,2,3]
Copy the code above → paste in your IDE → run main() → compare your output with this. If it matches, move to the next problem.

STEP 4 Code Explanation — Line by Line

Combines middle + reverse + merge. Time O(n).

🗣 How to say it in interview: First state brute force + its cost, then say “I will trade memory for time” (or “use two pointers / DP”), walk one dry-run example, then write code. Close with Time + Space + edge cases.
Problem 24 of 50 • Linked List + Math • LC 2

24. Add Two Numbers MEDIUM

Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation

🧩 Program / Problem: Add numbers stored reverse in lists.

STEP 1 Explanation in Details — Why This Works

Add digit by digit with carry. carry=sum/10, digit=sum%10.

STEP 2 Solution Logic — Step by Step

Dummy, carry=0. While l1 or l2 or carry: sum, digit, carry, append.

STEP 3 Code — Complete & Runnable in Java

✅ Complete file — copy into one .java file named after the class, run it. Includes import, class, solution method, main() with test, and helper classes (ListNode / TreeNode / Node) where needed.

// ALGORITHM - READ BEFORE CODE:
// 1. Understand input/output from Expected Output below.
// 2. Think brute force first, then optimise (see STEP 1-2 in explanation).
// 3. Dry-run with the sample input on paper - trace each variable.
// 4. Then run this code - if output matches Expected Output, logic is correct.
// COPY-PASTE READY - Paste in LeetCode / IntelliJ / VS Code and Run
// How to run: Create Solution.java, paste this file, run main() below.
// Read the comments - each block explains WHY, not just WHAT.
public class AddTwoNumbers {
    static class ListNode { int val; ListNode next; ListNode(int v){val=v;} }
    public ListNode addTwoNumbers(ListNode a, ListNode b) {
        // WHY: Create the helper structure - it trades a little memory for a lot of speed.
        ListNode dummy = new ListNode(0), tail = dummy; int carry = 0;
        // WHY: Keep going while condition holds - shrink / expand window or move pointers.
        while (a != null || b != null || carry != 0) {
            int sum = carry + (a != null ? a.val : 0) + (b != null ? b.val : 0);
            // WHY: Create the helper structure - it trades a little memory for a lot of speed.
            tail.next = new ListNode(sum % 10); carry = sum / 10; tail = tail.next;
            // WHY: Check the key condition - if true, we found the answer / edge case.
            if (a != null) a = a.next; if (b != null) b = b.next;
        }
        // WHY: Return here - we found the answer, no need to check more.
        return dummy.next;
    }
    static void print(ListNode h){ while(h!=null){ System.out.print(h.val+" "); h=h.next; } System.out.println(); }
    public static void main(String[] args) {
        // WHY: Create the helper structure - it trades a little memory for a lot of speed.
        ListNode a = new ListNode(2); a.next = new ListNode(4); a.next.next = new ListNode(3);
        // WHY: Create the helper structure - it trades a little memory for a lot of speed.
        ListNode b = new ListNode(5); b.next = new ListNode(6); b.next.next = new ListNode(4);
        print(new AddTwoNumbers().addTwoNumbers(a,b)); // 7 0 8
    }
}
// EXPECTED OUTPUT for sample above:
// Input: l1 = [2,4,3], l2 = [5,6,4]  // 342 + 465
// Output: [7,0,8]  // 807
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
▶ Try It Yourself — Expected Output
Input: l1 = [2,4,3], l2 = [5,6,4] // 342 + 465
Output: [7,0,8] // 807
Copy the code above → paste in your IDE → run main() → compare your output with this. If it matches, move to the next problem.

STEP 4 Code Explanation — Line by Line

Handles different lengths + final carry. Time O(max(n,m)).

🗣 How to say it in interview: First state brute force + its cost, then say “I will trade memory for time” (or “use two pointers / DP”), walk one dry-run example, then write code. Close with Time + Space + edge cases.
Read in order

Part 5 — Trees & BST

Problems 25–32 • Recursion + bounds + inorder. Draw the tree, then code.

Problem 25 of 50 • Tree DFS • LC 104

25. Maximum Depth of Binary Tree EASY

Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation

🧩 Program / Problem: Max depth of tree.

STEP 1 Explanation in Details — Why This Works

Depth=1+max(depth left, depth right). Null=0.

STEP 2 Solution Logic — Step by Step

If null 0. Return 1+max(depth(left),depth(right)).

STEP 3 Code — Complete & Runnable in Java

✅ Complete file — copy into one .java file named after the class, run it. Includes import, class, solution method, main() with test, and helper classes (ListNode / TreeNode / Node) where needed.

// ALGORITHM - READ BEFORE CODE:
// 1. Understand input/output from Expected Output below.
// 2. Think brute force first, then optimise (see STEP 1-2 in explanation).
// 3. Dry-run with the sample input on paper - trace each variable.
// 4. Then run this code - if output matches Expected Output, logic is correct.
// COPY-PASTE READY - Paste in LeetCode / IntelliJ / VS Code and Run
// How to run: Create Solution.java, paste this file, run main() below.
// Read the comments - each block explains WHY, not just WHAT.
public class MaxDepthTree {
    static class TreeNode { int val; TreeNode left,right; TreeNode(int v){val=v;} }
    public int maxDepth(TreeNode root) {
        // WHY: Check the key condition - if true, we found the answer / edge case.
        if (root == null) return 0;
        // WHY: Return here - we found the answer, no need to check more.
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }
    public static void main(String[] args) {
        TreeNode r = new TreeNode(3); r.left = new TreeNode(9); r.right = new TreeNode(20); r.right.left = new TreeNode(15); r.right.right = new TreeNode(7);
        System.out.println(new MaxDepthTree().maxDepth(r)); // 3
    }
}
// EXPECTED OUTPUT for sample above:
// Input: root = [3,9,20,null,null,15,7]
// Output: 3
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
▶ Try It Yourself — Expected Output
Input: root = [3,9,20,null,null,15,7]
Output: 3
Copy the code above → paste in your IDE → run main() → compare your output with this. If it matches, move to the next problem.

STEP 4 Code Explanation — Line by Line

Recursion depth = tree height. Time O(n).

🗣 How to say it in interview: First state brute force + its cost, then say “I will trade memory for time” (or “use two pointers / DP”), walk one dry-run example, then write code. Close with Time + Space + edge cases.

Next in Series

Next: Part 6 — Problems 26–30.

KnowledgeWala • LEARN TEACH GROW • knowledgewala.com