KnowledgeWala • Top 50 LeetCode Series • Part 1 of 10 • 5 Problems • ~40 min • 8 min per problem
Problems in this part: 1. Two Sum EASY, 2. Contains Duplicate EASY, 3. Valid Anagram EASY, 4. Group Anagrams MEDIUM, 5. Top K Frequent Elements MEDIUM
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: Given nums and target, return indices i,j where nums[i]+nums[j]==target.
Brute force tries every pair O(n²). HashMap remembers what we have seen. For each x, we need target-x. If seen before, we are done.
For each i: need=target-nums[i]. If need in map return [map[need],i]. Else put nums[i]->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 TwoSum {
public int[] twoSum(int[] nums, int target) {
// WHY: Create the helper structure - it trades a little memory for a lot of speed.
Map<Integer,Integer> map = new HashMap<>();
// WHY: Loop through every element once - we check each one exactly once, O(n).
for (int i = 0; i < nums.length; i++) {
int need = target - nums[i];
// WHY: Check the key condition - if true, we found the answer / edge case.
if (map.containsKey(need)) return new int[]{map.get(need), i};
// WHY: Remember this - store it so we can find it in O(1) later.
map.put(nums[i], i);
}
// WHY: Return here - we found the answer, no need to check more.
return new int[]{-1,-1};
}
public static void main(String[] args) {
TwoSum s = new TwoSum();
System.out.println(Arrays.toString(s.twoSum(new int[]{2,7,11,15}, 9))); // [0,1]
System.out.println(Arrays.toString(s.twoSum(new int[]{3,2,4}, 6))); // [1,2]
}
}
// EXPECTED OUTPUT for sample above:
// Input: nums = [2,7,11,15], target = 9
// Output: [0,1] // nums[0]+nums[1] = 2+7 = 9
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
nums = [2,7,11,15], target = 9[0,1] // nums[0]+nums[1] = 2+7 = 9main() → compare your output with this. If it matches, move to the next problem.map stores value -> index. need is complement. If found, pair done. Else store current. Time O(n), Space O(n).
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Return true if any value appears twice.
Use Set as seen. add() returns false if already present — duplicate in O(1).
Iterate, if !set.add(n) return true. End 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.
import java.util.*;
public class ContainsDuplicate {
public boolean containsDuplicate(int[] nums) {
// WHY: Create the helper structure - it trades a little memory for a lot of speed.
Set<Integer> seen = new HashSet<>();
// WHY: Loop through every element once - we check each one exactly once, O(n).
for (int n : nums) if (!seen.add(n)) return true;
// WHY: Return here - we found the answer, no need to check more.
return false;
}
public static void main(String[] args) {
ContainsDuplicate s = new ContainsDuplicate();
// WHY: Lookup in O(1) - did we see this before?
System.out.println(s.containsDuplicate(new int[]{1,2,3,1})); // true
// WHY: Lookup in O(1) - did we see this before?
System.out.println(s.containsDuplicate(new int[]{1,2,3,4})); // false
}
}
// EXPECTED OUTPUT for sample above:
// Input: nums = [1,2,3,1]
// Output: true // 1 appears twice
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
nums = [1,2,3,1]true // 1 appears twicemain() → compare your output with this. If it matches, move to the next problem.add() does hash+check in one step. False means duplicate. Time O(n), Space O(n).
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Check if t is anagram of s.
Anagrams have same character counts. Count with array size 26.
If lengths differ false. freq[26]++. For s +1, for t -1. Check all zero.
✅ 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 ValidAnagram {
public boolean isAnagram(String s, String t) {
// WHY: Check the key condition - if true, we found the answer / edge case.
if (s.length() != t.length()) return false;
int[] freq = new int[26];
// WHY: Loop through every element once - we check each one exactly once, O(n).
for (int i = 0; i < s.length(); i++) {
freq[s.charAt(i)-'a']++;
freq[t.charAt(i)-'a']--;
}
// WHY: Loop through every element once - we check each one exactly once, O(n).
for (int v : freq) if (v != 0) return false;
// WHY: Return here - we found the answer, no need to check more.
return true;
}
public static void main(String[] args) {
ValidAnagram s = new ValidAnagram();
System.out.println(s.isAnagram("anagram","nagaram")); // true
System.out.println(s.isAnagram("rat","car")); // false
}
}
// EXPECTED OUTPUT for sample above:
// Input: s = 'anagram', t = 'nagaram'
// Output: true
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
s = 'anagram', t = 'nagaram'truemain() → compare your output with this. If it matches, move to the next problem.Char-'a' gives 0-25. Net zero = same counts. Time O(n), Space O(1).
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Group strings that are anagrams.
Anagrams share same sorted form. eat/tea/ate -> aet. Use sorted string as Map key.
Sort chars of each s -> key. computeIfAbsent(key) list.add(s). Return values.
✅ 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 GroupAnagrams {
public List<List<String>> groupAnagrams(String[] strs) {
// WHY: Create the helper structure - it trades a little memory for a lot of speed.
Map<String,List<String>> map = new HashMap<>();
// WHY: Loop through every element once - we check each one exactly once, O(n).
for (String s : strs) {
// WHY: Sort first - after sorting, two pointers / binary search becomes possible.
char[] c = s.toCharArray(); Arrays.sort(c);
String key = new String(c);
// WHY: Remember this - store it so we can find it in O(1) later.
map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
}
// WHY: Return here - we found the answer, no need to check more.
return new ArrayList<>(map.values());
}
public static void main(String[] args) {
GroupAnagrams s = new GroupAnagrams();
System.out.println(s.groupAnagrams(new String[]{"eat","tea","tan","ate","nat","bat"}));
}
}
// EXPECTED OUTPUT for sample above:
// Input: strs = ['eat','tea','tan','ate','nat','bat']
// Output: [['eat','tea','ate'],['tan','nat'],['bat']]
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
strs = ['eat','tea','tan','ate','nat','bat'][['eat','tea','ate'],['tan','nat'],['bat']]main() → compare your output with this. If it matches, move to the next problem.computeIfAbsent creates list only first time. Sorting each string O(k log k).
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Return k most frequent elements.
Count freq. Min-heap size k — smallest freq on top, evict when >k.
Count via merge. Heap by value. Offer, if size>k poll. Extract keys.
✅ 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 TopKFrequent {
public int[] topKFrequent(int[] nums, int k) {
// WHY: Create the helper structure - it trades a little memory for a lot of speed.
Map<Integer,Integer> freq = new HashMap<>();
// WHY: Loop through every element once - we check each one exactly once, O(n).
for (int n : nums) freq.merge(n, 1, Integer::sum);
// WHY: Create the helper structure - it trades a little memory for a lot of speed.
PriorityQueue<Map.Entry<Integer,Integer>> heap = new PriorityQueue<>(Map.Entry.comparingByValue());
// WHY: Loop through every element once - we check each one exactly once, O(n).
for (var e : freq.entrySet()) { heap.offer(e); if (heap.size() > k) heap.poll(); }
int[] res = new int[k];
// WHY: Loop through every element once - we check each one exactly once, O(n).
for (int i = k-1; i >= 0; i--) res[i] = heap.poll().getKey();
// WHY: Return here - we found the answer, no need to check more.
return res;
}
public static void main(String[] args) {
TopKFrequent s = new TopKFrequent();
System.out.println(Arrays.toString(s.topKFrequent(new int[]{1,1,1,2,2,3}, 2))); // [1,2]
}
}
// EXPECTED OUTPUT for sample above:
// Input: nums = [1,1,1,2,2,3], k = 2
// Output: [1,2]
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
nums = [1,1,1,2,2,3], k = 2[1,2]main() → compare your output with this. If it matches, move to the next problem.Heap keeps only top k. Time O(n log k). Bucket sort O(n) alternative.
Next: Part 2 — Problems 6–10.
KnowledgeWala • LEARN TEACH GROW • knowledgewala.com