Sum of Two Values

Moderate
0/80
Average time to solve is 30m
profile
Contributed by
3 upvotes
Asked in companies
LinkedInIncedo Inc.Accolite

Problem statement

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.

Detailed explanation ( Input/output format, Notes, Images )
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.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= ‘T’ <= 10
1 <= ‘N’ <= 10^6
1 <= ‘K’ <= 10^6
1 <= ‘NUMS[i]’ <= 10^6

Time Limit: 1 sec
Sample Input 1:
1
4 10
4 3 5 7
Sample Output 1:
YES
Explanation For Sample Input 1:
The 2nd and 4th elements of ‘NUMS’ sum to 10, Hence the answer exists and is equal to [2 4]. Another accepted answer would be [4 2].
Sample Input 2:
2
5 2
4 8 3 5
4 6
3 3 3 4
Sample Output 2:
YES
YES
Hint

Think of a brute force solution.

Approaches (3)
Brute Force Approach:
  • 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.
Time Complexity

O(N ^ 2), where N is the size of the array NUMS.

 

There are a total of N*(N - 1)/2 pairs of indices for an array of size N. Hence the net time complexity is O(N ^ 2).

Space Complexity

O(1)

 

As we are using constant extra space.

Code Solution
(100% EXP penalty)
Sum of Two Values
Full screen
Console