Given an array of integers nums and a target k, find a pair of numbers from an array whose sum is equal to k and return their indices as output.

Example 1
Input: nums = [3, 2, 4] and K = 6
Output: [1, 2]
Explanation: after adding up values at index 1 and 2 , that adds up to the target 6.
Example 2
Input: nums = [3, 3] and K = 6
Output: [0,1]
Explanation: after adding up values at index 0 and 1 , that adds up to the target 6.
Constraints:

Contents

Using HashMap

The main intution behind this solution is, as per the problem statement x + y = k, given the value k, we have to find (x, y) pair. If we know one number x, then all we have to do is find the other number, which is k-x. So, in this approach we will loop through all elements of input array nums, and for every number at ith index x = nums[i], we will find if the other number for the pair k-x is visited or not using a HashMap.

Implementation steps:
public int[] twoSum(int[] array, int target) { // base case to find a pair we need atleast two elements. if(array == null || array.length < 2) { throw new IllegalArgumentException("input array should contain atleast two elements"); } Map<Integer, Integer> map = new HashMap<>(); for(int i=0; i<array.length; i++) { int current = array[i]; int diff = target - current; Integer pairIndex = map.get(diff); if(pairIndex != null) { // we found other number index which adds up to target k return new int[] {pairIndex, i}; } else { map.put(current, i); // store the number and its index } } return null; // none found }
Complexity Analysis:

Above code runs in O(n) time complexity where n is the size of the array, as we are looping through the array.
Space complexity is O(n) as we are storing elements into HashMap.

illustration:

Consider below example

Input Array : [2, 7, 11, 15] and Target = 18.

Step 1 We initialize an intermediate data structure HashMap to store element and it's index.

Step 2 Loop through elements and find if the other pair element visited or not.

Above implementations source code can be found at GitHub link for Java code