rakesh kumar

Posted on

# Array:Given an array of integers return indices of the two numbers that they add up to target

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target

``````Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
``````
``````Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
``````
``````Input: nums = [3,3], target = 6
Output: [0,1]
``````

Verify constraints
Are all the numbers are positive or there be negative

``````[1,3,7,9,12] or [-1,-3,-7,-9,-12]
``````

Are there duplicates no in array

``````[1,3,7,9,12] or [1,1,3,7,7,9]
``````

will there be always solution available
target-25

``````[1,3,7,9,12]  []
``````

Solution:

Writing Brute Force solution

``````[1,3,7,9,2]  t=11  [3,4]
``````
``````[1,3,7,9,2]  t=25  null
``````
``````[]  t=1  null
``````
``````[5]  t=5  null
``````
``````[1,6]  t=7  [0,1]
``````

Figure out solution without code

`````` 0 1 2 3 4
[1,3,7,9,2]  t=11  [3,4]
p1 p2

no to find= target-p[i]
11-1=10

then move array to find  which element contain 10
[1,3,7,9,2]
p1   p2

[1,3,7,9,2]
p1     p2

[1,3,7,9,2]
p1       p2
``````
`````` 0 1 2 3 4
[1,3,7,9,2]  t=11  [3,4]
p1 p2

no to find= target-p[i]
11-3=17

then move array to find  which element contain 7
[1,3,7,9,2]
p1   p2

[1,3,7,9,2]
p1     p2

[1,3,7,9,2]
p1       p2
``````

similary continue logic

First Methods

``````const find two sum= function(num,target){
for (int i = 0; i < nums.length; i++) {
const no to find=target-nums[i];
for(int j = i+1 ; j< nums.length ; j++)
{
if(no to find   == nums[j])
{
return [i,j];
}
}
}
}
``````

Another Methods

``````public static int[] sum(int[] nums , int target)
{
int[] ans = new int[2];
if(nums.length < 2)
{
return null;
}
for (int i = 0; i < nums.length; i++) {
for(int j = i+1 ; j< nums.length ; j++)
{
if(nums[i] + nums[j] == target)
{
ans[0] = i;
ans[1] = j;
return ans;
}
}
}
return null;
}
``````