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

Top 50 LeetCode — Part 4
Problems 16–20

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

Part 1 Part 2 Part 3 Part 4 • You are here Part 5 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 16 of 50 • Stack + Aux Stack • LC 155

16. Min Stack MEDIUM

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

🧩 Program / Problem: Stack with getMin in O(1).

STEP 1 Explanation in Details — Why This Works

Second stack minSt: each entry is min so far.

STEP 2 Solution Logic — Step by Step

Push both. Pop both. Top=data.top, getMin=min.top.

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.
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.
▶ Try It Yourself — Expected Output
Input: MinStack push -2,0,-3, getMin, pop, top, getMin
Output: getMin=-3, top=0, getMin=-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

Each min is min up to that point. Time O(1) all ops.

🗣 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 17 of 50 • Monotonic Stack • LC 739

17. Daily Temperatures MEDIUM

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

🧩 Program / Problem: Days until warmer temperature.

STEP 1 Explanation in Details — Why This Works

Monotonic decreasing stack of indices. When current > top, pop and answer.

STEP 2 Solution Logic — Step by Step

Stack indices. For i: while stack not empty and temps[i]>temps[top]: ans[top]=i-top, pop. Push i.

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.
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.
▶ Try It Yourself — Expected Output
Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
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

Stack keeps candidates waiting. Time O(n), each pushed/popped once.

🗣 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 18 of 50 • Monotonic Stack • LC 84

18. Largest Rectangle in Histogram HARD

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

🧩 Program / Problem: Largest rectangle in histogram.

STEP 1 Explanation in Details — Why This Works

For each bar, width = distance to previous smaller and next smaller. Stack increasing.

STEP 2 Solution Logic — Step by Step

Stack increasing. For i with sentinel 0: while top height > cur: h=pop, width=i-newTop-1. Max area.

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.
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.
▶ Try It Yourself — Expected Output
Input: heights = [2,1,5,6,2,3]
Output: 10
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

Sentinel 0 flushes stack. 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.
Read in order

Part 4 — Linked List

Problems 19–24 • Dummy + Fast/Slow + Reverse solve almost every list problem.

Problem 19 of 50 • Linked List • LC 206

19. Reverse Linked List EASY

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

🧩 Program / Problem: Reverse list iteratively.

STEP 1 Explanation in Details — Why This Works

Three pointers: prev, curr. Save next, point curr.next=prev, move.

STEP 2 Solution Logic — Step by Step

prev=null,curr=head. While curr: next=curr.next; curr.next=prev; prev=curr; curr=next. Return prev.

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 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.
▶ Try It Yourself — Expected Output
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
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

Draw 1->2->3: after step1 1->null, after step2 2->1, after step3 3->2->1. 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 20 of 50 • Linked List • LC 21

20. Merge Two Sorted Lists EASY

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

🧩 Program / Problem: Merge two sorted lists.

STEP 1 Explanation in Details — Why This Works

Dummy head + tail. Compare heads, attach smaller.

STEP 2 Solution Logic — Step by Step

dummy, tail. While both: attach smaller. Attach leftover. Return dummy.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.
// 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.
▶ Try It Yourself — Expected Output
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,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 avoids null-head edge. Time O(n+m), 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.

Next in Series

Next: Part 5 — Problems 21–25.

KnowledgeWala • LEARN TEACH GROW • knowledgewala.com