Trade O(1) average-case lookups for extra space. Count occurrences with a frequency map, or store previously seen values to answer "have I seen this before?" in O(1) per query.
Single pass through the array — each element is inserted and looked up at most once. Extra O(n) space for the map, where n is the number of distinct keys stored.
// ── 1. Frequency map — count occurrences ──────────────────────── Map<Integer, Integer> freq = new HashMap<>(); for (int n : nums) freq.merge(n, 1, Integer::sum); // freq[n]++ // ── 2. Existence / Two Sum style — seen map ────────────────────── Map<Integer, Integer> seen = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (seen.containsKey(complement)) return new int[]{ seen.get(complement), i }; // found pair seen.put(nums[i], i); // store value → index }