KnowledgeWala • Top 50 LeetCode Series • Part 3 of 10 • 5 Problems • ~40 min • 8 min per problem
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
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: All unique triplets summing to 0.
Sort. Fix i, two pointers l,r. Sum==0 record, skip dups. Sum<0 l++. Sum>0 r--.
Sort. Loop i skip dup i. While l<r handle 3 cases, skip dup l/r after found.
✅ 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.
nums = [-1,0,1,2,-1,-4][[-1,-1,2],[-1,0,1]]main() → compare your output with this. If it matches, move to the next problem.Sorting enables two-pointer O(n) per i. Total O(n²). Duplicate skipping gives uniqueness.
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Max area between two lines.
Area=min(h[l],h[r])*width. Move shorter side.
l=0,r=n-1,max=0. While l<r: area, update max, move shorter.
✅ 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.
height = [1,8,6,2,5,4,8,3,7]49main() → compare your output with this. If it matches, move to the next problem.Only moving shorter can raise min. Time O(n), Space O(1).
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Longest substring with all unique chars.
Window [start,end]. Map char->last index. If seen inside window, jump start.
Map lastSeen. For end: if contains c start=max(start,last+1). Put c->end. Max=max(max,end-start+1).
✅ 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.
s = 'abcabcbb'3 // 'abc'main() → compare your output with this. If it matches, move to the next problem.Dry run abcabcbb: window grows to abc (3), a repeats -> start=1, etc. Time O(n).
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Smallest substring of s containing all chars of t.
Need counts of t. Expand right, when valid shrink left, track min.
Count t. Expand r, if char in need increment, if equals need have++. While have==req: update min, shrink l.
✅ 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.
s = 'ADOBECODEBANC', t = 'ABC''BANC'main() → compare your output with this. If it matches, move to the next problem.Two pointers + two maps. Time O(n). Hardest sliding window.
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Check brackets balanced.
Push opening. For closing, pop must match.
Map pairs. For c: if opening push, else if empty or pop!=pair false. Return empty.
✅ 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.
s = '()[]{}'truemain() → compare your output with this. If it matches, move to the next problem.Use ArrayDeque not Stack class. Time O(n), Space O(n).
Next: Part 4 — Problems 16–20.
KnowledgeWala • LEARN TEACH GROW • knowledgewala.com