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

Top 50 LeetCode — Part 3
Problems 11–15

Problems in this part: 11. 3Sum MEDIUM, 12. Container With Most Water MEDIUM, 13. Longest Substring Without Repeating MEDIUM, 14. Minimum Window Substring HARD, 15. Valid Parentheses EASY

Part 1 Part 2 Part 3 • You are here Part 4 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 11 of 50 • Sorting + Two Pointers • LC 15

11. 3Sum MEDIUM

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

🧩 Program / Problem: All unique triplets summing to 0.

STEP 1 Explanation in Details — Why This Works

Sort. Fix i, two pointers l,r. Sum==0 record, skip dups. Sum<0 l++. Sum>0 r--.

STEP 2 Solution Logic — Step by Step

Sort. Loop i skip dup i. While l<r handle 3 cases, skip dup l/r after found.

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 ThreeSum {
    public List<List<Integer>> threeSum(int[] nums) {
        // WHY: Sort first - after sorting, two pointers / binary search becomes possible.
        Arrays.sort(nums);
        // WHY: Create the helper structure - it trades a little memory for a lot of speed.
        List<List<Integer>> res = new ArrayList<>();
        // WHY: Loop through every element once - we check each one exactly once, O(n).
        for (int i = 0; i < nums.length-2; i++) {
            // WHY: Check the key condition - if true, we found the answer / edge case.
            if (i > 0 && nums[i] == nums[i-1]) continue;
            int l = i+1, r = nums.length-1;
            // WHY: Keep going while condition holds - shrink / expand window or move pointers.
            while (l < r) {
                int sum = nums[i] + nums[l] + nums[r];
                // WHY: Check the key condition - if true, we found the answer / edge case.
                if (sum == 0) {
                    // WHY: Remember this - store it so we can find it in O(1) later.
                    res.add(List.of(nums[i], nums[l], nums[r]));
                    // WHY: Keep going while condition holds - shrink / expand window or move pointers.
                    while (l < r && nums[l] == nums[l+1]) l++;
                    // WHY: Keep going while condition holds - shrink / expand window or move pointers.
                    while (l < r && nums[r] == nums[r-1]) r--;
                    l++; r--;
                } else if (sum < 0) l++; else r--;
            }
        }
        // WHY: Return here - we found the answer, no need to check more.
        return res;
    }
    public static void main(String[] args) {
        ThreeSum s = new ThreeSum();
        System.out.println(s.threeSum(new int[]{-1,0,1,2,-1,-4})); // [[-1,-1,2],[-1,0,1]]
    }
}
// EXPECTED OUTPUT for sample above:
// Input: nums = [-1,0,1,2,-1,-4]
// Output: [[-1,-1,2],[-1,0,1]]
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
▶ Try It Yourself — Expected Output
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,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

Sorting enables two-pointer O(n) per i. Total O(n²). Duplicate skipping gives uniqueness.

🗣 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 12 of 50 • Two Pointers • LC 11

12. Container With Most Water MEDIUM

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

🧩 Program / Problem: Max area between two lines.

STEP 1 Explanation in Details — Why This Works

Area=min(h[l],h[r])*width. Move shorter side.

STEP 2 Solution Logic — Step by Step

l=0,r=n-1,max=0. While l<r: area, update max, move shorter.

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 ContainerWater {
    public int maxArea(int[] height) {
        int l = 0, r = height.length-1, max = 0;
        // WHY: Keep going while condition holds - shrink / expand window or move pointers.
        while (l < r) {
            // WHY: Keep the best answer seen so far.
            max = Math.max(max, Math.min(height[l], height[r]) * (r-l));
            // WHY: Check the key condition - if true, we found the answer / edge case.
            if (height[l] < height[r]) l++; else r--;
        }
        // WHY: Return here - we found the answer, no need to check more.
        return max;
    }
    public static void main(String[] args) {
        ContainerWater s = new ContainerWater();
        System.out.println(s.maxArea(new int[]{1,8,6,2,5,4,8,3,7})); // 49
    }
}
// EXPECTED OUTPUT for sample above:
// Input: height = [1,8,6,2,5,4,8,3,7]
// Output: 49
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
▶ Try It Yourself — Expected Output
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
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

Only moving shorter can raise min. 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 13 of 50 • Sliding Window + HashMap • LC 3

13. Longest Substring Without Repeating MEDIUM

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

🧩 Program / Problem: Longest substring with all unique chars.

STEP 1 Explanation in Details — Why This Works

Window [start,end]. Map char->last index. If seen inside window, jump start.

STEP 2 Solution Logic — Step by Step

Map lastSeen. For end: if contains c start=max(start,last+1). Put c->end. Max=max(max,end-start+1).

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 LongestSubstring {
    public int lengthOfLongestSubstring(String s) {
        // WHY: Create the helper structure - it trades a little memory for a lot of speed.
        Map<Character,Integer> map = new HashMap<>();
        int best = 0, start = 0;
        // WHY: Loop through every element once - we check each one exactly once, O(n).
        for (int end = 0; end < s.length(); end++) {
            char c = s.charAt(end);
            // WHY: Check the key condition - if true, we found the answer / edge case.
            if (map.containsKey(c)) start = Math.max(start, map.get(c)+1);
            // WHY: Remember this - store it so we can find it in O(1) later.
            map.put(c, end);
            // WHY: Keep the best answer seen so far.
            best = Math.max(best, end-start+1);
        }
        // WHY: Return here - we found the answer, no need to check more.
        return best;
    }
    public static void main(String[] args) {
        LongestSubstring s = new LongestSubstring();
        System.out.println(s.lengthOfLongestSubstring("abcabcbb")); // 3
        System.out.println(s.lengthOfLongestSubstring("pwwkew")); // 3
    }
}
// EXPECTED OUTPUT for sample above:
// Input: s = 'abcabcbb'
// Output: 3  // 'abc'
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
▶ Try It Yourself — Expected Output
Input: s = 'abcabcbb'
Output: 3 // 'abc'
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

Dry run abcabcbb: window grows to abc (3), a repeats -> start=1, etc. 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 14 of 50 • Sliding Window • LC 76

14. Minimum Window Substring HARD

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

🧩 Program / Problem: Smallest substring of s containing all chars of t.

STEP 1 Explanation in Details — Why This Works

Need counts of t. Expand right, when valid shrink left, track min.

STEP 2 Solution Logic — Step by Step

Count t. Expand r, if char in need increment, if equals need have++. While have==req: update min, shrink l.

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 MinWindow {
    public String minWindow(String s, String t) {
        // WHY: Create the helper structure - it trades a little memory for a lot of speed.
        Map<Character,Integer> need = new HashMap<>();
        // WHY: Loop through every element once - we check each one exactly once, O(n).
        for (char c : t.toCharArray()) need.merge(c, 1, Integer::sum);
        // WHY: Create the helper structure - it trades a little memory for a lot of speed.
        Map<Character,Integer> win = new HashMap<>();
        int have = 0, req = need.size(), l = 0, bl = 0, blen = Integer.MAX_VALUE;
        // WHY: Loop through every element once - we check each one exactly once, O(n).
        for (int r = 0; r < s.length(); r++) {
            char c = s.charAt(r);
            win.merge(c, 1, Integer::sum);
            // WHY: Check the key condition - if true, we found the answer / edge case.
            if (need.containsKey(c) && win.get(c).equals(need.get(c))) have++;
            // WHY: Keep going while condition holds - shrink / expand window or move pointers.
            while (have == req) {
                // WHY: Check the key condition - if true, we found the answer / edge case.
                if (r-l+1 < blen) { blen = r-l+1; bl = l; }
                char lc = s.charAt(l);
                win.merge(lc, -1, Integer::sum);
                // WHY: Check the key condition - if true, we found the answer / edge case.
                if (need.containsKey(lc) && win.get(lc) < need.get(lc)) have--;
                l++;
            }
        }
        // WHY: Return here - we found the answer, no need to check more.
        return blen == Integer.MAX_VALUE ? "" : s.substring(bl, bl+blen);
    }
    public static void main(String[] args) {
        MinWindow s = new MinWindow();
        System.out.println(s.minWindow("ADOBECODEBANC", "ABC")); // BANC
    }
}
// EXPECTED OUTPUT for sample above:
// Input: s = 'ADOBECODEBANC', t = 'ABC'
// Output: 'BANC'
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
▶ Try It Yourself — Expected Output
Input: s = 'ADOBECODEBANC', t = 'ABC'
Output: 'BANC'
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

Two pointers + two maps. Time O(n). Hardest sliding window.

🗣 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 3 — Stack

Problems 15–18 • Monotonic stack behind many Medium / Hard problems.

Problem 15 of 50 • Stack • LC 20

15. Valid Parentheses EASY

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

🧩 Program / Problem: Check brackets balanced.

STEP 1 Explanation in Details — Why This Works

Push opening. For closing, pop must match.

STEP 2 Solution Logic — Step by Step

Map pairs. For c: if opening push, else if empty or pop!=pair false. Return empty.

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 ValidParentheses {
    public boolean isValid(String s) {
        Deque<Character> st = new ArrayDeque<>();
        Map<Character,Character> pairs = Map.of(')', '(', '}', '{', ']', '[');
        // WHY: Loop through every element once - we check each one exactly once, O(n).
        for (char c : s.toCharArray()) {
            // WHY: Check the key condition - if true, we found the answer / edge case.
            if (pairs.containsValue(c)) st.push(c);
            // WHY: Otherwise - the other case, handle it separately.
            else if (st.isEmpty() || st.pop() != pairs.get(c)) return false;
        }
        // WHY: Return here - we found the answer, no need to check more.
        return st.isEmpty();
    }
    public static void main(String[] args) {
        ValidParentheses v = new ValidParentheses();
        System.out.println(v.isValid("()[]{}")); // true
        System.out.println(v.isValid("(]")); // false
    }
}
// EXPECTED OUTPUT for sample above:
// Input: s = '()[]{}'
// Output: true
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
▶ Try It Yourself — Expected Output
Input: s = '()[]{}'
Output: true
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

Use ArrayDeque not Stack class. Time O(n), Space 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 4 — Problems 16–20.

KnowledgeWala • LEARN TEACH GROW • knowledgewala.com