Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

分类: technical

难度: easy

标签:

答题技巧

["Optimal solution uses hash map (one-pass hash)","Time O(n), Space O(n)","Brute force O(n²) is acceptable for junior roles","Must clarify: cannot use same element twice","Follow-up possible: multiple solutions? duplicates in array?","Return indices, not values"]

参考答案

Hash map solution: ```javascript function twoSum(nums, target) { const map = new Map(); for (let i = 0; i < nums.length; i++) { const complement = target - nums[i]; if (map.has(complement)) { return [map.get(complement), i]; } map.set(nums[i], i); } return []; } ```

Technical
Easy

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

100 views

Answer Tips

["Optimal solution uses hash map (one-pass hash)","Time O(n), Space O(n)","Brute force O(n²) is acceptable for junior roles","Must clarify: cannot use same element twice","Follow-up possible: multiple solutions? duplicates in array?","Return indices, not values"]

Sample Answer

Hash map solution: ```javascript function twoSum(nums, target) { const map = new Map(); for (let i = 0; i < nums.length; i++) { const complement = target - nums[i]; if (map.has(complement)) { return [map.get(complement), i]; } map.set(nums[i], i); } return []; } ```

Start Mock Interview Practice

Improve your interview skills and confidence with AI mock interviews