Two Sum
Software Developer Associate with over 4 years of experience in the IT industry comprising Systems Administration and Change Management, Software Configuration Management, Build and Release Management Process Engineering.
Given an array of integer nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input : nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Solution:
- Here you are given an array of integers (
nums) and a target integer (target), and you need to find two numbers in the array that add up to the target.
Initialize a HashMap (hm) to store the numbers encountered so far as keys and their corresponding indices as values.
Iterate through the
numsarray using aforloop. For each element in the array, calculate the required number (req_num) to achieve the target sum by subtracting the current number from the target.Check if the
req_numexists in theHashMap(hm) using thecontainsKeymethod. If it exists, it means you've found two numbers that add up to the target.If the
req_numexists in theHashMap, create an arrayarrwith the indices of the two numbers (the index ofreq_numand the current indexi) and returnarr.If the
req_numdoes not exist in theHashMap, add the current number and its index to theHashMapfor future reference.If no two numbers are found that add up to the target during the loop, return
nullto indicate that there is no solution.
import java.util.Arrays;
import java.util.HashMap;
public class TwoSum {
public static void main(String[] args) {
int[] nums= {2,7,11,15};
System.out.println(Arrays.toString(twoSum(nums,9)));
}
public static int[] twoSum(int[] nums, int target)
{
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
for(int i=0; i<nums.length; i++)
{
int req_num = target - nums[i];
if(hm.containsKey(req_num))
{
int[] arr = {hm.get(req_num),i};
return arr;
}
hm.put(nums[i],i);
}
return null;
}
}
It has a time complexity of O(n), where n is the number of elements in the nums array, as it iterates through the array only once.