1. Two Sum
Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target.
Each input has exactly one solution, and you may not use the same element twice. Return the two indices in any order.
Input: nums = [2,7,11,15], target = 9 Output: [0,1]
Explanation: nums[0] + nums[1] = 2 + 7 = 9.
Input: nums = [3,2,4], target = 6 Output: [1,2]
Input: nums = [3,3], target = 6 Output: [0,1]
Constraints
2 <= nums.length <= 10^4-10^9 <= nums[i], target <= 10^9- Exactly one valid answer exists.
💡 Hint 1
A brute-force pair check is O(n²). Can you avoid re-scanning the array?
💡 Hint 2
For each number, the partner you need is target - num. Remember what you have already seen, and where.
Try it yourself first ✎
Solutions stick better after a real attempt. Peek when you're ready.
Approach
Walk the array once and keep a hash map from value → index of everything seen so far. For each nums[i], the number that completes the pair is target - nums[i]; if it is already in the map, you have the answer. Checking before inserting guarantees you never pair an element with itself.
function twoSum(nums, target) {
const seen = new Map();
for (let i = 0; i < nums.length; i++) {
const need = target - nums[i];
if (seen.has(need)) return [seen.get(need), i];
seen.set(nums[i], i);
}
return [];
}class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
Integer j = seen.get(target - nums[i]);
if (j != null) return new int[] { j, i };
seen.put(nums[i], i);
}
return new int[0];
}
}No submissions yet. Press Submit to run your code against every test.
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
function twoSum(nums, target) {
}Run your code to see results here.