I went straight to the hash map approach which is the right call, but I fumbled a bit explaining why I was trading space for time.
Start by clarifying the problem constraints (e.g., return any valid pair, indices order, 1-indexed vs 0-indexed) and then propose a hash map solution that stores each element's value and index as you iterate. Explain how this achieves O(n) time and handles duplicates, negatives, and no-solution cases by checking for the complement before inserting the current element.
Pro tip: Mention that you check for the complement before inserting the current element to avoid using the same index twice, and explicitly state that the hash map approach works for negative numbers because it relies on exact value matching, not ordering.
Ask about input constraints (e.g., array size, integer range), expected output format (indices order, 0-indexed or 1-indexed), and whether multiple solutions exist. Confirm that distinct indices are required and that the array is unsorted.
Explain that you'll use a hash map to store each element's value and its index as you traverse the array once. For each element, compute the complement (target - current) and check if it's already in the map.
Describe the loop: for each index i, compute complement; if complement exists in map, return [map[complement], i]; otherwise, store current element and index in map. Emphasize that you check before inserting to avoid using the same element twice.
Explain that duplicates are handled naturally because the map stores the first occurrence's index, and if a later duplicate forms a pair, it will be found. Negative numbers work because the complement calculation is arithmetic. If no pair exists, return an empty array or a sentinel value like [-1, -1].
State that time complexity is O(n) and space complexity is O(n) due to the hash map. Mention that this is optimal for unsorted arrays, and briefly compare with sorting-based O(n log n) approach if asked.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.