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

Top 50 LeetCode — Part 1
Problems 1–5

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

Part 1 • You are here Part 2 Part 3 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 1 of 50 • HashMap • LC 1

1. Two Sum EASY

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.

STEP 1 Explanation in Details — Why This Works

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.

STEP 2 Solution Logic — Step by Step

For each i: need=target-nums[i]. If need in map return [map[need],i]. Else put nums[i]->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 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.
▶ Try It Yourself — Expected Output
Input: nums = [2,7,11,15], target = 9
Output: [0,1] // nums[0]+nums[1] = 2+7 = 9
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

map stores value -> index. need is complement. If found, pair done. Else store current. 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.
Problem 2 of 50 • HashSet • LC 217

2. Contains Duplicate EASY

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

🧩 Program / Problem: Return true if any value appears twice.

STEP 1 Explanation in Details — Why This Works

Use Set as seen. add() returns false if already present — duplicate in O(1).

STEP 2 Solution Logic — Step by Step

Iterate, if !set.add(n) return true. End return false.

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 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.
▶ Try It Yourself — Expected Output
Input: nums = [1,2,3,1]
Output: true // 1 appears twice
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

add() does hash+check in one step. False means duplicate. 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.
Problem 3 of 50 • Counting • LC 242

3. Valid Anagram EASY

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

🧩 Program / Problem: Check if t is anagram of s.

STEP 1 Explanation in Details — Why This Works

Anagrams have same character counts. Count with array size 26.

STEP 2 Solution Logic — Step by Step

If lengths differ false. freq[26]++. For s +1, for t -1. Check all zero.

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 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.
▶ Try It Yourself — Expected Output
Input: s = 'anagram', t = 'nagaram'
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

Char-'a' gives 0-25. Net zero = same counts. 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 4 of 50 • HashMap + Sorting • LC 49

4. Group Anagrams MEDIUM

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

🧩 Program / Problem: Group strings that are anagrams.

STEP 1 Explanation in Details — Why This Works

Anagrams share same sorted form. eat/tea/ate -> aet. Use sorted string as Map key.

STEP 2 Solution Logic — Step by Step

Sort chars of each s -> key. computeIfAbsent(key) list.add(s). Return values.

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 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.
▶ Try It Yourself — Expected Output
Input: strs = ['eat','tea','tan','ate','nat','bat']
Output: [['eat','tea','ate'],['tan','nat'],['bat']]
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

computeIfAbsent creates list only first time. Sorting each string O(k log k).

🗣 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 5 of 50 • Heap • LC 347

5. Top K Frequent Elements MEDIUM

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

🧩 Program / Problem: Return k most frequent elements.

STEP 1 Explanation in Details — Why This Works

Count freq. Min-heap size k — smallest freq on top, evict when >k.

STEP 2 Solution Logic — Step by Step

Count via merge. Heap by value. Offer, if size>k poll. Extract keys.

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

Heap keeps only top k. Time O(n log k). Bucket sort O(n) alternative.

🗣 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 2 — Problems 6–10.

KnowledgeWala • LEARN TEACH GROW • knowledgewala.com