Monday 25 July 2016

Two elements sum to x

Given an array of n numbers and another number x, determines whether or not there exist two elements in the array whose sum is exactly x.

Approach: Sort the array and use two pointers one at the start and the other at the end. Increment the start pointer if the sum is less than the target, decrement if the sum is greater else break out of the loop.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/* To find the pair of elements in an array if the sum is equal to the given number */
#include<iostream>
#include<algorithm>
using namespace std;

int main(){
    int arr[6] = {1, 4, 45, 6, 10, -8};
    int n = sizeof(arr) / sizeof(arr[0]);
    sort(arr, arr + n);
    int i = 0, j = n - 1, k = 16;
    int flag = 0;
    while(i < j){
            if(arr[i] + arr[j] == k){
                flag = 1;
                break;
            } else if(arr[i] + arr[j] > k){
                j--;
            } else{
                i++;
            }
    }
    if(flag){
        cout << arr[i] << " + " << arr[j] << " add upto " << k << endl;
    } else{
        cout << "No such pair exists" << endl;
    }
    return 0;
}
Share:

4 comments:

  1. Replies
    1. Thanks Devashish! It comes with practice and the more we explore.

      Delete
  2. array has 6 elements and n is set to 52. Will it work? Is it a mistake?
    Please clarify.

    ReplyDelete
    Replies
    1. Hi TSR,

      Thank you for pointing out the mistake. I have rectified it.

      Delete

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive