KnowledgeWala • Top 50 LeetCode Series • Part 5 of 10 • 5 Problems • ~40 min • 8 min per problem
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
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.
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Detect cycle in linked list.
Floyd: slow 1, fast 2. If cycle, fast laps slow.
slow=head,fast=head. While fast and fast.next: slow++, fast+=2, if equal true. Return false.
✅ 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.
head = [3,2,0,-4], pos = 1true // cycle at node 2main() → compare your output with this. If it matches, move to the next problem.In cycle distance shrinks by 1 each step, must meet. Time O(n), Space O(1).
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Remove nth from end in one pass.
Fast moves n+1 ahead (with dummy). Then both move. Slow ends before target.
Dummy->head. fast=dummy. Move fast n+1. Move both to end. slow.next=slow.next.next.
✅ 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.
head = [1,2,3,4,5], n = 2[1,2,3,5] // removed 4main() → compare your output with this. If it matches, move to the next problem.Dummy handles removing head. One pass O(n).
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Reorder L0->Ln->L1->Ln-1...
Find middle, reverse second half, merge alternating.
Middle via slow/fast. Reverse second. Merge one from first, one from reversed.
✅ 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.
head = [1,2,3,4][1,4,2,3]main() → compare your output with this. If it matches, move to the next problem.Combines middle + reverse + merge. Time O(n).
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Add numbers stored reverse in lists.
Add digit by digit with carry. carry=sum/10, digit=sum%10.
Dummy, carry=0. While l1 or l2 or carry: sum, digit, carry, append.
✅ 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.
l1 = [2,4,3], l2 = [5,6,4] // 342 + 465[7,0,8] // 807main() → compare your output with this. If it matches, move to the next problem.Handles different lengths + final carry. Time O(max(n,m)).
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Max depth of tree.
Depth=1+max(depth left, depth right). Null=0.
If null 0. Return 1+max(depth(left),depth(right)).
✅ 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.
root = [3,9,20,null,null,15,7]3main() → compare your output with this. If it matches, move to the next problem.Recursion depth = tree height. Time O(n).
Next: Part 6 — Problems 26–30.
KnowledgeWala • LEARN TEACH GROW • knowledgewala.com