array
of integers, find two numbers such that they sum up to a specific target.coupleSum
should return the indices of the two numbers in the array, where index1 must be less than index2. Input Array : {2, 3, 4, 7}
Target : 7
Output : {2, 3}
HashMap
is a sound choice.
key
and value
that you will store in the HashMap
. Let's consider the example shown above. Iterating across the array [2, 3, 4, 7], at each step let us store the key as target - arr[i]
, and the value i+1
(since the output is not zero-indexed). Now, if we are at i=1
, or arr[i] = 3
and store key = 7 - 3=4
and value = 1 + 1 = 2
, then when we get to the next index i = 2
, we just need to check if they key arr[i] = 4
exists in the HashMap
. public static int[] coupleSum(int[] numbers, int target) { }
C
Java
Python