Arrays & Hashing
Core idea
Section titled “Core idea”A HashMap turns “search the array again” (O(n)) into “look it up” (O(1)). Ask yourself: “What do I wish I already knew while scanning?” Then store that in a map.
A prefix sum turns “sum of a range” into a subtraction: sum(i..j) = prefix[j+1] - prefix[i].
Templates
Section titled “Templates”// Frequency mapMap<Integer, Integer> freq = new HashMap<>();for (int x : nums) freq.put(x, freq.getOrDefault(x, 0) + 1);// or: freq.merge(x, 1, Integer::sum);
// For lowercase letters, an int[26] is faster and simplerint[] count = new int[26];for (char c : s.toCharArray()) count[c - 'a']++;
// Prefix sum (size n+1 so there are no off-by-one headaches)int[] prefix = new int[n + 1];for (int i = 0; i < n; i++) prefix[i + 1] = prefix[i] + nums[i];// sum of nums[l..r] inclusive = prefix[r + 1] - prefix[l]
// "Seen before" map: one pass, check then insertMap<Integer, Integer> seen = new HashMap<>();for (int i = 0; i < n; i++) { int need = /* what would complete the answer */ 0; if (seen.containsKey(need)) { /* found */ } seen.put(nums[i], i);}Problems
Section titled “Problems”Problem: Two Sum (Easy) — LC 1
Approach (say out loud): “Brute force checks every pair, which is O(n²). Instead, while scanning, I’ll keep a map from value to index. For each number I check whether target - num is already in the map. I check before inserting so I never use the same element twice.”
Java:
class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> seen = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int need = target - nums[i]; if (seen.containsKey(need)) { return new int[]{seen.get(need), i}; } seen.put(nums[i], i); } return new int[]{-1, -1}; }}Complexity: O(n) time, O(n) space
Edge cases: duplicates like [3,3] with target 6 (works because we check before inserting), negative numbers.
Problem: Contains Duplicate (Easy) — LC 217
Approach (say out loud): “I’ll add each number to a HashSet. add returns false if it’s already there, and then I return true.”
Java:
class Solution { public boolean containsDuplicate(int[] nums) { Set<Integer> set = new HashSet<>(); for (int x : nums) { if (!set.add(x)) return true; } return false; }}Complexity: O(n) time, O(n) space. (Sorting first gives O(n log n) time and O(1) extra space. Mention this trade-off.)
Edge cases: empty or single-element array → false.
Problem: Group Anagrams (Medium) — LC 49
Approach (say out loud): “Anagrams have the same letter counts. I’ll build a canonical key for each word, either the sorted string or a count signature, and group words in a map from key to list.”
Java:
class Solution { public List<List<String>> groupAnagrams(String[] strs) { Map<String, List<String>> groups = new HashMap<>(); for (String s : strs) { int[] count = new int[26]; for (char c : s.toCharArray()) count[c - 'a']++; StringBuilder key = new StringBuilder(); for (int c : count) key.append(c).append('#'); groups.computeIfAbsent(key.toString(), k -> new ArrayList<>()).add(s); } return new ArrayList<>(groups.values()); }}Complexity: O(n · k) time, where k is the max word length (sorted-key version: O(n · k log k)). O(n · k) space.
Edge cases: empty strings "" group together. The # separator stops counts like 1,11 and 11,1 from colliding.
Problem: Top K Frequent Elements (Medium) — LC 347
Approach (say out loud): “First count frequencies with a map. A frequency can be at most n, so I can use bucket sort: bucket[f] holds all numbers with frequency f. Then I walk from the highest bucket down until I have k numbers. That’s O(n). A min-heap of size k also works in O(n log k).”
Java:
class Solution { public int[] topKFrequent(int[] nums, int k) { Map<Integer, Integer> freq = new HashMap<>(); for (int x : nums) freq.merge(x, 1, Integer::sum);
List<Integer>[] bucket = new List[nums.length + 1]; for (Map.Entry<Integer, Integer> e : freq.entrySet()) { int f = e.getValue(); if (bucket[f] == null) bucket[f] = new ArrayList<>(); bucket[f].add(e.getKey()); }
int[] result = new int[k]; int idx = 0; for (int f = nums.length; f >= 1 && idx < k; f--) { if (bucket[f] == null) continue; for (int num : bucket[f]) { if (idx == k) break; result[idx++] = num; } } return result; }}Complexity: O(n) time, O(n) space
Edge cases: k equals the number of unique elements, all elements the same.
Problem: Product of Array Except Self (Medium) — LC 238
Approach (say out loud): “No division allowed. The answer at i is (product of everything to the left) × (product of everything to the right). First I fill the result with left products, then I sweep from the right with a running product. That gives O(1) extra space.”
Java:
class Solution { public int[] productExceptSelf(int[] nums) { int n = nums.length; int[] res = new int[n]; res[0] = 1; for (int i = 1; i < n; i++) { res[i] = res[i - 1] * nums[i - 1]; // product of the left side } int right = 1; for (int i = n - 1; i >= 0; i--) { res[i] *= right; right *= nums[i]; } return res; }}Complexity: O(n) time, O(1) extra space (the output array doesn’t count)
Edge cases: one zero (only that index is non-zero), two or more zeros (everything is 0). The prefix/suffix approach handles both without special code.
Problem: Longest Consecutive Sequence (Medium) — LC 128
Approach (say out loud): “Sorting would be O(n log n), but they want O(n). I’ll put everything in a HashSet. A number starts a sequence only if num - 1 isn’t in the set. From each start I count upward. Each number is visited at most twice, so it’s O(n).”
Java:
class Solution { public int longestConsecutive(int[] nums) { Set<Integer> set = new HashSet<>(); for (int x : nums) set.add(x); int best = 0; for (int x : set) { if (!set.contains(x - 1)) { // x starts a sequence int len = 1; while (set.contains(x + len)) len++; best = Math.max(best, len); } } return best; }}Complexity: O(n) time, O(n) space
Edge cases: empty array → 0, duplicates (the set removes them), negative numbers. Loop over the set, not the array, so duplicates don’t cause repeated scans.
Problem: Subarray Sum Equals K (Medium) — LC 560
Approach (say out loud): “Negatives are allowed, so a sliding window won’t work. If the prefix sum up to j is sum, a subarray ending at j sums to k exactly when an earlier prefix equals sum - k. I keep a map from prefix sum to how many times it has appeared, starting with {0: 1} for the empty prefix.”
Java:
class Solution { public int subarraySum(int[] nums, int k) { Map<Integer, Integer> count = new HashMap<>(); count.put(0, 1); int sum = 0, result = 0; for (int x : nums) { sum += x; result += count.getOrDefault(sum - k, 0); count.merge(sum, 1, Integer::sum); } return result; }}Complexity: O(n) time, O(n) space
Edge cases: k = 0, negative numbers, the whole array being the answer (that’s why we seed {0: 1}).
Problem: Maximum Subarray, Kadane's (Medium) — LC 53
Approach (say out loud): “At each index I decide: extend the previous subarray, or start fresh here? If the running sum is negative, it only hurts, so I start fresh. I track the best sum seen so far.”
Java:
class Solution { public int maxSubArray(int[] nums) { int current = nums[0], best = nums[0]; for (int i = 1; i < nums.length; i++) { current = Math.max(nums[i], current + nums[i]); best = Math.max(best, current); } return best; }}Complexity: O(n) time, O(1) space
Edge cases: all negative numbers (the answer is the largest single element, so initialize with nums[0], not 0), a single element.