Tutorialspoint
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].
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].
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)
ArraysNumberCapgeminiPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Create a hash map to store numbers and their indices
 Step 2: Iterate through the array from left to right
 Step 3: For each element, calculate its complement (target - current element)
 Step 4: Check if the complement exists in the hash map
 Step 5: If complement exists, return the stored index and current index
 Step 6: If complement doesn't exist, store current element and its index in hash map
 Step 7: Continue until the pair is found

Submitted Code :