Sunday, 15 July 2012


Check whether  two given arrays are permutation of each other in O(n) time by using O(1) space.
#include<iostream>
#include<set>
#include<algorithm>

     
bool ArraysPermute(int  array1[],int size1, int  array2[], int size2)
{      
       if( size1  != size2)          
           return false;
       else
       {      
           std::set<int> first_set(array1, array1+size1);
           std::set<int> second_set(array2, array2+size2);
     
           std::pair<std::set<int>::iterator,std::set<int>::iterator> myPair=std::mismatch(first_set.begin(),first_set.end(),second_set.begin());
         
           if( *myPair.first != *myPair.second)
               
                return false;
            else
                return true;
       }
}


int main()
{    
    int array1[] ={1,2,3,5};
    int array2[]={1,2,4,3};
   
    if(ArraysPermute(array1,sizeof(array1)/sizeof(int), array2, sizeof(array2)/sizeof(int)))
        std::cout<< " Arrays are permutation of each other\n";
    else
        std::cout<< " Arrays are not permutation of each other\n";
     
    return 0;
}

Wednesday, 12 October 2011

Find a set of pairs from a set of integers

The solution is implemented in C++ by using STL ( Standard Template Library).

#include<map>
#include<iostream>

int main()
{
std::multimap<int,int> A;
int num[4]={2,4,5,6};
for(int i=0;i<4;++i)
{
   for(int j=0;j<4;++j)
   {
      if(i!=j)
      {
         A.insert(std::pair<int,int>(num[i],num[j]));
      }
   }
}

for( auto &k : A)
  std::cout<<k.first<<","<<k.second<<"\n";

return 0;
}

2. Either (a,b) or (b,a) is allowed
#include<map>
#include<iostream>

int main()
{
std::multimap<int,int> A;
int num[4]={2,4,5,6};
for(int i=0;i<4;++i)
{
   for(int j=0;j<4;++j)
   {
      if(i!=j)
      {
         A.insert(std::pair<int,int>(num[i],num[j]));
      }
   }
}

for( auto &k : A)
  std::cout<<k.first<<","<<k.second<<"\n";

return 0;
}