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

Top 50 LeetCode — Part 2
Problems 6–10

Problems in this part: 6. Product of Array Except Self MEDIUM, 7. Longest Consecutive Sequence MEDIUM, 8. Best Time to Buy and Sell Stock EASY, 9. Maximum Subarray MEDIUM, 10. Valid Palindrome EASY

Part 1 Part 2 • You are here 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 6 of 50 • Prefix / Suffix • LC 238

6. Product of Array Except Self MEDIUM

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

🧩 Program / Problem: Return ans[i]=product of all except nums[i]. No division, O(n).

STEP 1 Explanation in Details — Why This Works

Left product * right product. First pass stores prefix. Second multiplies suffix.

STEP 2 Solution Logic — Step by Step

ans[i]=prefix. prefix*=nums[i]. Then suffix=1 from right, ans[i]*=suffix, suffix*=nums[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 ProductExceptSelf {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length; int[] ans = new int[n]; int pre = 1;
        // WHY: Loop through every element once - we check each one exactly once, O(n).
        for (int i = 0; i < n; i++) { ans[i] = pre; pre *= nums[i]; }
        int suf = 1;
        // WHY: Loop through every element once - we check each one exactly once, O(n).
        for (int i = n-1; i >= 0; i--) { ans[i] *= suf; suf *= nums[i]; }
        // WHY: Return here - we found the answer, no need to check more.
        return ans;
    }
    public static void main(String[] args) {
        ProductExceptSelf s = new ProductExceptSelf();
        System.out.println(Arrays.toString(s.productExceptSelf(new int[]{1,2,3,4}))); // [24,12,8,6]
    }
}
// EXPECTED OUTPUT for sample above:
// Input: nums = [1,2,3,4]
// Output: [24,12,8,6]
// 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,4]
Output: [24,12,8,6]
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

First loop: product left of i. Second: multiply product right. Time O(n), Space O(1) extra.

🗣 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 7 of 50 • HashSet • LC 128

7. Longest Consecutive Sequence MEDIUM

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

🧩 Program / Problem: Longest consecutive numbers, O(n).

STEP 1 Explanation in Details — Why This Works

Sort is O(n log n). HashSet O(1) lookup. Only start at sequence start (no n-1).

STEP 2 Solution Logic — Step by Step

Put all in set. For n if !contains(n-1) count while contains(curr+1). Track max.

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 LongestConsecutive {
    public int longestConsecutive(int[] nums) {
        // WHY: Create the helper structure - it trades a little memory for a lot of speed.
        Set<Integer> set = new HashSet<>();
        // WHY: Loop through every element once - we check each one exactly once, O(n).
        for (int n : nums) set.add(n);
        int best = 0;
        // WHY: Loop through every element once - we check each one exactly once, O(n).
        for (int n : set) {
            // WHY: Check the key condition - if true, we found the answer / edge case.
            if (!set.contains(n-1)) {
                int cur = n, len = 1;
                // WHY: Keep going while condition holds - shrink / expand window or move pointers.
                while (set.contains(cur+1)) { cur++; len++; }
                // WHY: Keep the best answer seen so far.
                best = Math.max(best, len);
            }
        }
        // WHY: Return here - we found the answer, no need to check more.
        return best;
    }
    public static void main(String[] args) {
        LongestConsecutive s = new LongestConsecutive();
        System.out.println(s.longestConsecutive(new int[]{100,4,200,1,3,2})); // 4
    }
}
// EXPECTED OUTPUT for sample above:
// Input: nums = [100,4,200,1,3,2]
// Output: 4  // 1,2,3,4
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
▶ Try It Yourself — Expected Output
Input: nums = [100,4,200,1,3,2]
Output: 4 // 1,2,3,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

Guard !contains(n-1) makes it O(n): each number counted 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 8 of 50 • Greedy • LC 121

8. Best Time to Buy and Sell Stock EASY

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

🧩 Program / Problem: Max profit from one buy then sell.

STEP 1 Explanation in Details — Why This Works

Track min price so far. Profit today = price-min. Keep max.

STEP 2 Solution Logic — Step by Step

min=INF,best=0. For p: min=min(min,p); best=max(best,p-min).

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 BestTimeStock {
    public int maxProfit(int[] prices) {
        int min = Integer.MAX_VALUE, best = 0;
        // WHY: Loop through every element once - we check each one exactly once, O(n).
        for (int p : prices) { min = Math.min(min, p); best = Math.max(best, p - min); }
        // WHY: Return here - we found the answer, no need to check more.
        return best;
    }
    public static void main(String[] args) {
        BestTimeStock s = new BestTimeStock();
        System.out.println(s.maxProfit(new int[]{7,1,5,3,6,4})); // 5
    }
}
// EXPECTED OUTPUT for sample above:
// Input: prices = [7,1,5,3,6,4]
// Output: 5  // buy 1, sell 6
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
▶ Try It Yourself — Expected Output
Input: prices = [7,1,5,3,6,4]
Output: 5 // buy 1, sell 6
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

One pass. 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 9 of 50 • Kadane • LC 53

9. Maximum Subarray MEDIUM

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

🧩 Program / Problem: Largest sum of contiguous subarray.

STEP 1 Explanation in Details — Why This Works

Kadane: extend or start fresh. cur=max(nums[i],cur+nums[i]).

STEP 2 Solution Logic — Step by Step

cur=nums[0],best=nums[0]. For i: cur=max(...); best=max(best,cur).

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 MaximumSubarray {
    public int maxSubArray(int[] nums) {
        int cur = nums[0], best = nums[0];
        // WHY: Loop through every element once - we check each one exactly once, O(n).
        for (int i = 1; i < nums.length; i++) {
            // WHY: Keep the best answer seen so far.
            cur = Math.max(nums[i], cur + nums[i]);
            // WHY: Keep the best answer seen so far.
            best = Math.max(best, cur);
        }
        // WHY: Return here - we found the answer, no need to check more.
        return best;
    }
    public static void main(String[] args) {
        MaximumSubarray s = new MaximumSubarray();
        System.out.println(s.maxSubArray(new int[]{-2,1,-3,4,-1,2,1,-5,4})); // 6
    }
}
// EXPECTED OUTPUT for sample above:
// Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
// Output: 6  // [4,-1,2,1]
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
▶ Try It Yourself — Expected Output
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6 // [4,-1,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

If cur negative, starting fresh is better. 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.
Read in order

Part 2 — Strings, Two Pointers & Sliding Window

Problems 10–14 • Two pointers + window = most reusable pattern.

Problem 10 of 50 • Two Pointers • LC 125

10. Valid Palindrome EASY

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

🧩 Program / Problem: Check palindrome ignoring non-alphanumeric, case-insensitive.

STEP 1 Explanation in Details — Why This Works

Two pointers l,r. Skip non-alnum, compare lowercased.

STEP 2 Solution Logic — Step by Step

While l<r: skip, if lower(l)!=lower(r) false, l++,r--. Return true.

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 ValidPalindrome {
    public boolean isPalindrome(String s) {
        int l = 0, r = s.length()-1;
        // WHY: Keep going while condition holds - shrink / expand window or move pointers.
        while (l < r) {
            // WHY: Keep going while condition holds - shrink / expand window or move pointers.
            while (l < r && !Character.isLetterOrDigit(s.charAt(l))) l++;
            // WHY: Keep going while condition holds - shrink / expand window or move pointers.
            while (l < r && !Character.isLetterOrDigit(s.charAt(r))) r--;
            // WHY: Check the key condition - if true, we found the answer / edge case.
            if (Character.toLowerCase(s.charAt(l)) != Character.toLowerCase(s.charAt(r))) return false;
            l++; r--;
        }
        // WHY: Return here - we found the answer, no need to check more.
        return true;
    }
    public static void main(String[] args) {
        ValidPalindrome s = new ValidPalindrome();
        System.out.println(s.isPalindrome("A man, a plan, a canal: Panama")); // true
        System.out.println(s.isPalindrome("race a car")); // false
    }
}
// EXPECTED OUTPUT for sample above:
// Input: s = 'A man, a plan, a canal: Panama'
// Output: true
// If your output matches, your logic is correct. If not, re-read STEP 2 logic.
▶ Try It Yourself — Expected Output
Input: s = 'A man, a plan, a canal: Panama'
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

Skipping is key. 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.

Next in Series

Next: Part 3 — Problems 11–15.

KnowledgeWala • LEARN TEACH GROW • knowledgewala.com