Friday, 10 February 2012

Amazon written Test Question:

Here is one of Amazon's written Question which one of my friend got.
1. Convert an array "a1a2a3....b1b2b3...c1c2c3..." to "a1b1c1a2b2c2a3b3c3..." in-place.
 
Here is my code with time complexity O(n) and space complexity O(1).
This code works for both positive and negative numbers



#include<stdio.h>

#define N 4
int a[3*N]={1,2,3,4,5,6,7,8,9,10,11,12};
int main()
{
    int i,min,max,band,j,k,save,temp;
    //find min & max O(n).
    for(i=0;i<3*N;i++)
    { if(a[i]<min)
       min=a[i];
      if(a[i]>max)
       max=a[i];
    }
    band=max-min+1;
   
    // code to arrange the elements
    for(i=0;i<3*N;i++)
    {
              if(a[i]<=max)
              {
                           j=k=i;
                           save=a[i];
                           while(1)
                           {
                              if(j<N)
                                k=3*j;
                              else if(j<2*N)
                                k=3*(j-N)+1;
                              else
                                k=3*(j-2*N)+2;
               
                                temp=a[k];
                                a[k]=save+band;
                                save=temp;
               
                                j=k;
               
                                if(k==i)
                                 break;
                             }
                }
     
    }
   
    for(i=0;i<3*N;i++)
    { a[i]=a[i]-band;
      printf("%d  ",a[i]);
    }    
   
    return(0);
}


No comments:

Post a Comment