Home Arrays Find two elements in an array such that their sum equals ‘K’.

# Find two elements in an array such that their sum equals ‘K’.

0 comment

Question: Given an array of n elements. Find two elements such that their sum is equal to a given element ‘K’ ?

Input: arr [] = {42, 23, 15, 16, 8, 4} and element K = 58
Output: 16, 42

To understand the problem statement a little more, we are given with an array of ‘n’ elements and another element ‘K’. We need to find if there exists 2 elements in the given array such that their sum equals the given element K. The array is not sorted.

One simple solution to this is, for each input element check whether there is any element whose sum is K. This can be done by using 2 simple for loops. The code for this solution can be written as:-

#include<stdio.h>

void twoElementsSumK(int arr[], int size, int K)
{
int i,j;

// first loop
for(i=0;i<size;i++)
{
// second loop
for(j=i+1;j<size;j++)
{
// check for sum equal to K
if(arr[i] + arr[j] == K)
{
// print the elements and return
printf("The elements found are :- %d %d",arr[i],arr[j]);
return;
}
}
}

// If we reach here means that no element was found.
printf("No elements found");
}

//driver program to test the function
int main(void)
{
int arr[] = {42, 23, 15, 16, 8, 4};

printf("Enter value of K:- ");
int K;

scanf("%d", &K);

twoElementsSumK(arr,6,K);

return 0;
}


Time Complexity:- O(n2)
Space Complexity:- O(1)