Debug School

rakesh kumar
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

two-sum

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

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Enter fullscreen mode Exit fullscreen mode
Input: nums = [3,3], target = 6
Output: [0,1]
Enter fullscreen mode Exit fullscreen mode

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

[1,3,7,9,12] or [-1,-3,-7,-9,-12]
Enter fullscreen mode Exit fullscreen mode

Are there duplicates no in array

[1,3,7,9,12] or [1,1,3,7,7,9]
Enter fullscreen mode Exit fullscreen mode

will there be always solution available
target-25

[1,3,7,9,12]  []
Enter fullscreen mode Exit fullscreen mode

Solution:

Writing Brute Force solution

[1,3,7,9,2]  t=11  [3,4]
Enter fullscreen mode Exit fullscreen mode
[1,3,7,9,2]  t=25  null
Enter fullscreen mode Exit fullscreen mode
[]  t=1  null
Enter fullscreen mode Exit fullscreen mode
[5]  t=5  null
Enter fullscreen mode Exit fullscreen mode
[1,6]  t=7  [0,1]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
 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
Enter fullscreen mode Exit fullscreen mode

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];
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)