Approach
Use a JavaScript Map to store number→index pairs. For each element, check if target - num exists in the map. Map.has() and Map.get() are O(1) average.
Complexity Analysis
Key Insight
Tip: Use
Mapover plain objects{}for this pattern —Maphandles all key types correctly (including numbers) and has explicithas/get/setmethods that are clearer in intent.
JavaScript Solution
javascript// Problem: Two Sum with Map // Language: JavaScript // Difficulty: Easy // Time Complexity: O(n) // Space Complexity: O(n) /** * @param {number[]} nums * @param {number} target * @return {number[]} */ function twoSum(nums, target) { const seen = new Map(); // number -> index for (let i = 0; i < nums.length; i++) { const complement = target - nums[i]; // If complement was seen before, return both indices if (seen.has(complement)) { return [seen.get(complement), i]; } seen.set(nums[i], i); } return []; // guaranteed to have a solution }