
Problem
Solution
Submissions
Two Sum
Certification: Basic Level
Accuracy: 18.18%
Submissions: 22
Points: 5
Write a JavaScript function to find two numbers in an array that add up to a specific target. Return the indices of the two numbers such that they add up to the target. You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example 1
- Input: nums = [2, 7, 11, 15], target = 9
- Output: [0, 1]
- Explanation:
- We need to find two numbers that sum to 9.
- nums[0] = 2 and nums[1] = 7. 2 + 7 = 9, which equals our target.
- Therefore, we return the indices [0, 1].
- We need to find two numbers that sum to 9.
Example 2
- Input: nums = [3, 2, 4], target = 6
- Output: [1, 2]
- Explanation:
- We need to find two numbers that sum to 6. nums[1] = 2 and nums[2] = 4.
- 2 + 4 = 6, which equals our target.
- Therefore, we return the indices [1, 2].
- We need to find two numbers that sum to 6. nums[1] = 2 and nums[2] = 4.
Constraints
- 2 ≤ nums.length ≤ 10^4
- -10^9 ≤ nums[i] ≤ 10^9
- -10^9 ≤ target ≤ 10^9
- Only one valid answer exists
- Time Complexity: O(n)
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a hash map to store the numbers and their indices as you iterate
- For each number, calculate what its complement would be (target - current number)
- Check if the complement exists in the hash map
- If the complement exists, return the current index and the complement's index
- If not found, add the current number and its index to the hash map
- Continue until you find the pair