LOVE BABBAR 450 questions series Solutions


  1.     reverse an array                                                                        :Array

1.      void rvereseArray(int arr[], int start, int end)

2.      {

3.          while (start < end)

4.          {

5.              swap(arr[start],arr[end]);

6.              start++;

7.              end--;

8.          }

9.      }  

  =>using recursion : 

void revereseArray(int arr[], int start, int end)

{

    if (start >= end) return;

    swap(arr[start],arr[end]);     

    // Recursive Function calling

    revereseArray(arr, start + 1, end - 1);

      =>using python slicing

def reverseList(A):

  print( A[::-1])

 

2.             Find max and min element of an array                            : Array

int mn=INT_MAX,mx=INT_MIN;

for (int i = 0; i < n; ++i)

     {

         if(a[i]<mn) mn=a[i];

         if(a[i]>mx) mx=a[i];

     }

cout<<mn<<" "<<mx;

  =>

 sort(a,a+n);

 cout<<a[0]<<" "<<a[n-1];

 

                              click here for: Maximum and minimum of an array using minimum number of comparisons

                 

3.           Find “kth” max and min element of an array                    :  Array                                        

sort(a,a+n);

cout<<a[k-1]<<" "<<a[n-k]; //kth min and max

 

4.       Given an array which consists of only 0,1 and 2. Sort the array                        without using any sorting algo  : Array

Input: 0 2 1 2 0

Output:0 0 1 2 2

int c0=0,c1=0,c2=0;

forint i=0;i<n;i++){

    if(a[i]==0) c0++;

    else if(a[i]==1) c1++;

    else  c2++;

}

int i=0;

for( i=0;i<c0;++i)  a[i]=0

for( i=c0;i<c0+c1;++i)  a[i]=1

while(c2--){

    a[i++]=2;

}

 

5.           Move all the –ve elements to one side  of an array         :  Array                                        

Input: -12, 11, -13, -5, 6, -7, 5, -3, -6

Output: -12 -13 -5 -7 -3 -6 11 6 5

Note: Order of elements is not important here.

int j = 0;

    for (int i = 0; i < n; i++) {

        if (arr[i] < 0) {

            if (i != j)

                swap(arr[i], arr[j]);

            j++;

        }

    }

 

 

 

 

Comments

Popular posts from this blog

c++ oops

Takeoff (hackerearth.3, datastructure, array 1-D)

Aptitude tricks