KnowledgeWala • Top 50 LeetCode Series • Part 4 of 10 • 5 Problems • ~40 min • 8 min per problem
Problems in this part: 16. Min Stack MEDIUM, 17. Daily Temperatures MEDIUM, 18. Largest Rectangle in Histogram HARD, 19. Reverse Linked List EASY, 20. Merge Two Sorted Lists 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: Stack with getMin in O(1).
Second stack minSt: each entry is min so far.
Push both. Pop both. Top=data.top, getMin=min.top.
✅ 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.
import java.util.*;
public class MinStack {
private Deque<Integer> data = new ArrayDeque<>();
private Deque<Integer> mins = new ArrayDeque<>();
// WHY: Keep the best answer seen so far.
public void push(int v) { data.push(v); mins.push(mins.isEmpty() ? v : Math.min(v, mins.peek())); }
public void pop() { data.pop(); mins.pop(); }
public int top() { return data.peek(); }
public int getMin() { return mins.peek(); }
public static void main(String[] args) {
// WHY: Create the helper structure - it trades a little memory for a lot of speed.
MinStack s = new MinStack();
s.push(-2); s.push(0); s.push(-3);
System.out.println(s.getMin()); // -3
s.pop();
System.out.println(s.top()); // 0
System.out.println(s.getMin()); // -2
}
}
// EXPECTED OUTPUT for sample above:
// Input: MinStack push -2,0,-3, getMin, pop, top, getMin
// Output: getMin=-3, top=0, getMin=-2
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
MinStack push -2,0,-3, getMin, pop, top, getMingetMin=-3, top=0, getMin=-2main() → compare your output with this. If it matches, move to the next problem.Each min is min up to that point. Time O(1) all ops.
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Days until warmer temperature.
Monotonic decreasing stack of indices. When current > top, pop and answer.
Stack indices. For i: while stack not empty and temps[i]>temps[top]: ans[top]=i-top, pop. Push i.
✅ 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.
import java.util.*;
public class DailyTemperatures {
public int[] dailyTemperatures(int[] temps) {
int[] ans = new int[temps.length];
Deque<Integer> st = new ArrayDeque<>();
// WHY: Loop through every element once - we check each one exactly once, O(n).
for (int i = 0; i < temps.length; i++) {
// WHY: Keep going while condition holds - shrink / expand window or move pointers.
while (!st.isEmpty() && temps[i] > temps[st.peek()]) {
int prev = st.pop(); ans[prev] = i - prev;
}
st.push(i);
}
// WHY: Return here - we found the answer, no need to check more.
return ans;
}
public static void main(String[] args) {
DailyTemperatures s = new DailyTemperatures();
System.out.println(Arrays.toString(s.dailyTemperatures(new int[]{73,74,75,71,69,72,76,73})));
}
}
// EXPECTED OUTPUT for sample above:
// Input: temperatures = [73,74,75,71,69,72,76,73]
// Output: [1,1,4,2,1,1,0,0]
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
temperatures = [73,74,75,71,69,72,76,73][1,1,4,2,1,1,0,0]main() → compare your output with this. If it matches, move to the next problem.Stack keeps candidates waiting. Time O(n), each pushed/popped once.
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Largest rectangle in histogram.
For each bar, width = distance to previous smaller and next smaller. Stack increasing.
Stack increasing. For i with sentinel 0: while top height > cur: h=pop, width=i-newTop-1. Max area.
✅ 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.
import java.util.*;
public class LargestRectangle {
public int largestRectangleArea(int[] heights) {
Deque<Integer> st = new ArrayDeque<>();
int max = 0;
// WHY: Loop through every element once - we check each one exactly once, O(n).
for (int i = 0; i <= heights.length; i++) {
int cur = (i == heights.length) ? 0 : heights[i];
// WHY: Keep going while condition holds - shrink / expand window or move pointers.
while (!st.isEmpty() && cur < heights[st.peek()]) {
int h = heights[st.pop()];
int w = st.isEmpty() ? i : i - st.peek() - 1;
// WHY: Keep the best answer seen so far.
max = Math.max(max, h * w);
}
st.push(i);
}
// WHY: Return here - we found the answer, no need to check more.
return max;
}
public static void main(String[] args) {
LargestRectangle s = new LargestRectangle();
System.out.println(s.largestRectangleArea(new int[]{2,1,5,6,2,3})); // 10
}
}
// EXPECTED OUTPUT for sample above:
// Input: heights = [2,1,5,6,2,3]
// Output: 10
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
heights = [2,1,5,6,2,3]10main() → compare your output with this. If it matches, move to the next problem.Sentinel 0 flushes stack. Time O(n).
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Reverse list iteratively.
Three pointers: prev, curr. Save next, point curr.next=prev, move.
prev=null,curr=head. While curr: next=curr.next; curr.next=prev; prev=curr; curr=next. Return prev.
✅ 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 ReverseLinkedList {
static class ListNode { int val; ListNode next; ListNode(int v){val=v;} }
public ListNode reverseList(ListNode head) {
ListNode prev = null, curr = head;
// WHY: Keep going while condition holds - shrink / expand window or move pointers.
while (curr != null) {
ListNode nxt = curr.next; curr.next = prev; prev = curr; curr = nxt;
}
// WHY: Return here - we found the answer, no need to check more.
return prev;
}
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);
// WHY: Create the helper structure - it trades a little memory for a lot of speed.
ReverseLinkedList s = new ReverseLinkedList();
print(s.reverseList(h)); // 3 2 1
}
}
// EXPECTED OUTPUT for sample above:
// Input: head = [1,2,3,4,5]
// Output: [5,4,3,2,1]
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
head = [1,2,3,4,5][5,4,3,2,1]main() → compare your output with this. If it matches, move to the next problem.Draw 1->2->3: after step1 1->null, after step2 2->1, after step3 3->2->1. Time O(n), Space O(1).
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Merge two sorted lists.
Dummy head + tail. Compare heads, attach smaller.
dummy, tail. While both: attach smaller. Attach leftover. Return dummy.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.
// WHY: Sort first - after sorting, two pointers / binary search becomes possible.
public class MergeTwoSortedLists {
static class ListNode { int val; ListNode next; ListNode(int v){val=v;} }
public ListNode mergeTwoLists(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;
// WHY: Keep going while condition holds - shrink / expand window or move pointers.
while (a != null && b != null) {
// WHY: Check the key condition - if true, we found the answer / edge case.
if (a.val <= b.val) { tail.next = a; a = a.next; } else { tail.next = b; b = b.next; }
tail = tail.next;
}
tail.next = (a != null ? a : b);
// 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(1); a.next = new ListNode(2); a.next.next = new ListNode(4);
// WHY: Create the helper structure - it trades a little memory for a lot of speed.
ListNode b = new ListNode(1); b.next = new ListNode(3); b.next.next = new ListNode(4);
// WHY: Create the helper structure - it trades a little memory for a lot of speed.
print(new MergeTwoSortedLists().mergeTwoLists(a,b)); // 1 1 2 3 4 4
}
}
// EXPECTED OUTPUT for sample above:
// Input: list1 = [1,2,4], list2 = [1,3,4]
// Output: [1,1,2,3,4,4]
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
list1 = [1,2,4], list2 = [1,3,4][1,1,2,3,4,4]main() → compare your output with this. If it matches, move to the next problem.Dummy avoids null-head edge. Time O(n+m), Space O(1).
Next: Part 5 — Problems 21–25.
KnowledgeWala • LEARN TEACH GROW • knowledgewala.com