Two Sum

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.

  1. Iterate through the nums array using a for loop. 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.

  2. Check if the req_num exists in the HashMap (hm) using the containsKey method. If it exists, it means you've found two numbers that add up to the target.

  3. If the req_num exists in the HashMap, create an array arr with the indices of the two numbers (the index of req_num and the current index i) and return arr.

  4. If the req_num does not exist in the HashMap, add the current number and its index to the HashMap for future reference.

  5. If no two numbers are found that add up to the target during the loop, return null to 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.