KnowledgeWala • Top 50 LeetCode Series • Part 2 of 10 • 5 Problems • ~40 min • 8 min per problem
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
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: Return ans[i]=product of all except nums[i]. No division, O(n).
Left product * right product. First pass stores prefix. Second multiplies suffix.
ans[i]=prefix. prefix*=nums[i]. Then suffix=1 from right, ans[i]*=suffix, suffix*=nums[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 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.
nums = [1,2,3,4][24,12,8,6]main() → compare your output with this. If it matches, move to the next problem.First loop: product left of i. Second: multiply product right. Time O(n), Space O(1) extra.
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Longest consecutive numbers, O(n).
Sort is O(n log n). HashSet O(1) lookup. Only start at sequence start (no n-1).
Put all in set. For n if !contains(n-1) count while contains(curr+1). Track max.
✅ 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.
nums = [100,4,200,1,3,2]4 // 1,2,3,4main() → compare your output with this. If it matches, move to the next problem.Guard !contains(n-1) makes it O(n): each number counted once.
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Max profit from one buy then sell.
Track min price so far. Profit today = price-min. Keep max.
min=INF,best=0. For p: min=min(min,p); best=max(best,p-min).
✅ 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.
prices = [7,1,5,3,6,4]5 // buy 1, sell 6main() → compare your output with this. If it matches, move to the next problem.One pass. Time O(n), Space O(1).
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Largest sum of contiguous subarray.
Kadane: extend or start fresh. cur=max(nums[i],cur+nums[i]).
cur=nums[0],best=nums[0]. For i: cur=max(...); best=max(best,cur).
✅ 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.
nums = [-2,1,-3,4,-1,2,1,-5,4]6 // [4,-1,2,1]main() → compare your output with this. If it matches, move to the next problem.If cur negative, starting fresh is better. Time O(n), Space O(1).
Read in 4 steps: 1 Explanation → 2 Logic → 3 Code → 4 Code Explanation
🧩 Program / Problem: Check palindrome ignoring non-alphanumeric, case-insensitive.
Two pointers l,r. Skip non-alnum, compare lowercased.
While l<r: skip, if lower(l)!=lower(r) false, l++,r--. Return true.
✅ 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.
s = 'A man, a plan, a canal: Panama'truemain() → compare your output with this. If it matches, move to the next problem.Skipping is key. Time O(n), Space O(1).
Next: Part 3 — Problems 11–15.
KnowledgeWala • LEARN TEACH GROW • knowledgewala.com