Sum of Two Values

Posted: 22 Apr, 2021
Difficulty: Moderate


Try Problem

You are given an array of positive integers, ‘NUMS’, and provided with an integer ‘K’. Your take is to find out whether it is possible to find two distinct elements of ‘NUMS’ whose sum is equal to ‘K’.

By distinct we mean the index of the elements should be distinct, not necessarily their value.

Input Format:
The first line contains an integer ‘T’, which denotes the number of test cases to be run.

Then, the ‘T’ test cases follow.

The first line of each test case contains two positive integers, ‘N’ (denoting the size of the array ‘NUMS’) and ‘K’.

The second line of each test case contains ‘N’ space-separated positive integers denoting the array elements.
Output Format:
For each test case, print the indexes(1 indexed) of the two elements which sum up to ‘K’. If an answer does not exist, print -1 -1 instead. If multiple answers exist, print any of them.

The output will be checked by the system, for a correct answer "YES" will be printed otherwise "NO" will be printed.

The output of each test case will be printed in a separate line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= ‘T’ <= 10
1 <= ‘N’ <= 10^6
1 <= ‘K’ <= 10^6
1 <= ‘NUMS[i]’ <= 10^6

Time Limit: 1 sec
Approach 1
  • Look into every pair of numbers of NUMS(using 2 nested loops) and check if any of them satisfy the required conditions.
  • If any pair of numbers sum up to K, return their indices, otherwise, continue for the remaining pairs.
  • If no pair satisfies the condition, return -1 -1 at the end.
Try Problem