Saturday, April 7, 2012

Program 6TH in C++

PROBLEM STATEMENT :

Find two no’s in a sorted array whose sum =X ?
i gave a solution whose complexity is O(N) .. Anyone with reduced time complexity?



SOLUTION:


#include <iostream.h>
#include <cstdio>
#include <list.h>
#include <unistd.h>
#include <vector.h>

using namespace std;

int main()
{
int val=0;
int sum=0;
int flag=1;
int diff=0;
int i=0,j;

list<int> num1;

//Entering Array

cout<<"\n\nEnter numbers for the array :\n\n";

while(true)
{
cout<<"\n\nEnter : ";
cin>>val;
if(cin.good())
{
num1.push_back(val);
continue;
}
else
{
cout<<"\n\nYou entered a non integral value \n\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cin.sync();
break;
}
}
num1.sort();
vector<int> num (num1.begin(),num1.end());
num1.clear();
//Entering the sum user wants to find

cout<<"\n\nEnter the sum you want to find : ";
while(true)
{
cout<<"\n\nEnter : ";
cin>>sum;

if(cin.good())
{
break;
}
else
{
cout<<"\n\nYou entered a non integral value \n\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cin.sync();
continue;
}
}

if(num.back()>sum)
{
num.pop_back();
}
j=num.size()-1;

//Required loop to find the numbers if present

while(i < j)
{
diff=sum-num[i];
if(diff < num.back())
{
while(diff < num.back())
{
num.pop_back();
}
j=num.size()-1;
continue;
}
else
if(diff == num.back())
{
flag=0;
break;
}
i++;
}
if(flag == 0)
{
cout<<"\n\nThe numbers are at index : "<<i<<" and "<<num.size()-1;
cout<<"\n\nThe numbers are : "<<num[i]<<" and "<<num.back();
cout<
}
else
{
cout<<"\n\n No such numbers are present int the array \n\n";
}
}

5 comments:

  1. Using only arrays, it can be done as
    Suppose the sorted array given is a;

    int i=0;
    int size=sizeof(a)/sizeof(int);

    if(sum > (a[size-1]+a[size-2]) || sum < a[0])
    {
    cout<<"not possible";
    exit(0);
    }
    while(i < size-1)
    if(sum>(a[i]+a[size-1]))
    i++;
    elseif(sum <(a[i]+a[size-1]))
    size--;
    else
    {
    flag=0;
    break;
    }
    }

    if(flag==0)
    //found at i and size-1
    else
    //not found

    ReplyDelete
  2. I think it's still O(n) complexity.
    To be precise O(n/2) ~ O(n)

    ReplyDelete
    Replies
    1. Yes..but constant factor is improved for certain cases.

      Delete
  3. Maam, You have used here:

    num1.sort();

    which is itself N*log(N) function.. so you cant claim your method to run in linear time. Anyway if the i/p is sorted then you can say so...

    ReplyDelete
    Replies
    1. Le'me clear your confusion...

      First read the question..
      There its properly written that you are given a sorted array.
      As I have taken input from user end, that will not be sorted ofcourse..and hence I have used an inbuilt method sort.Its not a requirement by d ways. You can ignore.

      and second..
      read my first comment..dere is another solution..hope u can check that too.

      Thanks by d ways for ur precious time.

      Delete