Trade space for time — a
HashMap/HashSetturns O(n²) scans into O(n).
Most array problems that feel like "check every pair" can be reduced to a single pass by remembering what you've seen in a hash structure. Lookups are O(1).
- "Have I seen this value before?" →
HashSet - "What index/count maps to this value?" →
HashMap - Counting frequencies, grouping, deduping.
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (seen.containsKey(want(nums[i]))) { /* found */ }
seen.put(nums[i], i);
}| Problem | Difficulty | Solution |
|---|---|---|
| Contains Duplicate | 🟢 | todo |
| Valid Anagram | 🟢 | todo |
| Two Sum | 🟢 | TwoSum.java |
| Group Anagrams | 🟡 | todo |
| Top K Frequent Elements | 🟡 | todo |
| Product of Array Except Self | 🟡 | todo |
| Longest Consecutive Sequence | 🟡 | todo |