Tutorialspoint
Problem
Solution
Submissions

Two Sum

Certification: Basic Level Accuracy: 38.89% Submissions: 234 Points: 5

Write a Java program to implement the twoSum(int[] nums, int target) function, which finds indices of two numbers in an array such that they add up to a specific 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:
    • nums[0] = 2 → looking for 7
    • nums[1] = 7 → found complement
    • Return [0, 1] since 2 + 7 = 9
Example 2
  • Input: nums = [3, 2, 4], target = 6
  • Output: [1, 2]
  • Explanation:
    • nums[1] = 2 → looking for 4
    • nums[2] = 4 → found complement
    • Return [1, 2] since 2 + 4 = 6
Constraints
  • 2 ≤ nums.length ≤ 10^4
  • -10^9 ≤ nums[i] ≤ 10^9
  • -10^9 ≤ target ≤ 10^9
  • Time Complexity: O(n)
  • Space Complexity: O(n)
ArraysNumberIBMDeloitte
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 HashMap to store values and their indices as you iterate through the array
  • For each element, check if its complement (target - current element) exists in the HashMap
  • If found, return the indices of the current element and its complement
  • Otherwise, add the current element and its index to the HashMap

Steps to solve by this approach:

 Step 1: Create a HashMap to store array elements and their indices.
 Step 2: Iterate through the array one element at a time.
 Step 3: For each element, calculate its complement (target - current element).
 Step 4: Check if the complement exists in the HashMap.
 Step 5: If found, return the indices of both numbers.
 Step 6: If not found, add the current element and its index to the HashMap.
 Step 7: Continue until a solution is found or the array is exhausted.

Submitted Code :