Thursday, October 31, 2013

Diameter of a tree (longest leaf to leaf path)

I  do  not  know  what  was  GeeksforGeeks  algorithm  for  this  question.  I  did  not  get  a  bit  of  that.
But  this  is  my  code  which  has  passed  all  the  cases  from  interviewstreet.com.  You  can  yourself check   second  question  in   the  link  below

https://www.interviewstreet.com/recruit/test/start/sample


Here  is  my  code..  Hope  it  is  easily  understood

In  this  we  are  taking  that  both  the  leaves  have  common  source (which  may  be  root  or  any  other)
which  is  passed  into  the  function diameterOfTree()

Leaf  to  Leaf  path  from  that  node will  be  1+lh+rh

And  maximum  of  all  that  is  calculated

int maximum(int a,int b)
{
    if(a>=b)
        return a;
    else
        return b;
}  


int max=0;

int height(node* root)
{
    if(root!=NULL)
    {  
    int lh=height(root->left);
    int rh=height(root->right);
 
    return 1+maximum(lh,rh);
    }
    return 0;
}




int diameterOfTree(node * root)
{
    if(root!=NULL)
    {
    int temp=1+height(root->left)+height(root->right);
        if(temp>max)
            max=temp;
    diameterOfTree(root->left);
    diameterOfTree(root->right);
    }
    return max;
}

Thursday, October 24, 2013

Q. Generate output array such that it contains product of all elements except itself without division operator

INPUT             { 5 ,4, 3, 2, 1 }
OUTPUT          {24,30,40,60,120}

as a[0]=(4*3*2*1)=24
    a[1]=(5*3*2*1)


In  this  we  can  maintain  two  arrays  lh[]  and  rh[]

where  lh[i]= a[0] * a[1]*........*a[i-1]

and  rh[i]= a[i+1] * a[i+2]*........*a[n]  where  n  is  the  last  index  of  array

Here  is    my    code



#include<stdio.h>
int main()
{
int arr[5]={5,4,3,2,1};
int lh[5];//  will  contain  the  product  of  all  elements to  the  left
int rh[5];//  will  contain  the  product  of  all  elements to  the  right
int prod=1;
for(int k=0;k<5;k++)
{
lh[k]=prod;
prod=prod*arr[k]; }
prod=1;
for(int k=4;k>=0;k--)
{
rh[k]=prod;
prod=prod*arr[k]; }
for(int k=0;k<5;k++)
arr[k]=lh[k]*rh[k];
for(int k=0;k<5;k++)
printf("%d\t",arr[k]);
return 0;


Please  tell  me  if  any  optimizations  are  required..................



Wednesday, October 23, 2013

Q. Given a list of integers find out the biggest interval that has all the numbers in the given list

INPUT  1,8,4,6,3,2,7,11;


Possible  candidates  will  be  1,2,3,4  and  6,7,8  as  they  are  the  continous  elements  present  in  the  input  array

But  1,2,3,4  is  having  more  length  so  it  will  be  the  answer

OUTPUT  [1,4];


METHOD  1

Sort  all  elements  and  check for  the  biggest  interval  in  the  sorted  array

1.  After  using  merge  sort  ,  
     int length=1;//  length  will  be  our  answer
     int maxYet=1;

     for(int i=1 to n)
     {
      if(a[i]==a[i-1])
      {
       maxYet++;
     }
       else
       //resetset  maxYet  and  compare
        {
          if(maxYet>length)
           length=maxYet;
      
          maxYet=1;
        } 
      
     }

Time Complexity=O(n logn)
Space Complexity=O(1)


METHOD  2

It  really  took  time  to  think  that  one   

It  involves  hash...

1.  Scan  all the  elements  and  hash  in  2  hashmaps  (visited  and  present) all  elements.
2.  int  length=1,maxYet=1;
    visited[element]=0;
   present[element]=1;
3.  For  every  element  if  not  visited   , check  if  consecutive  predecessors  are  present  in  array  and  mark  them  as  visited

4.  Similarly  do  for  consecutive  successor  elements

5. Now  higher-lower  will  be  our  length,  if  that  is  maximum  than  previous  one  then  it  is  taken  as  result.





#include<iostream>
#include<map>
#include<string>

using namespace std;
typedef map<int,int> mapping;

int main() 
{
mapping visited;
mapping present;

int length=1,res1=-1,res2=-1;
int arr[10]={1,7,4,6,3,10,2,9,13,11};

for(int k=0;k<10;k++)
{
visited[arr[k]]=0;
present[arr[k]]=1;
}


for(int k=0;k<10;k++)
{
int element=arr[k];int lower=arr[k],higher=arr[k];

if(visited[element]==0)
{
while(present[element]==1)
{
lower=element;
visited[element]=1;
element--;
}

element=arr[k]+1;
while(present[element]==1)
{
higher=element;
visited[element]=1;
element++;
}

if((higher-lower)>length)
{
res1=lower;res2=higher;length=higher-lower;
}
}
}
if(res1==-1 && res2==-1)
printf("No consecutive element");
else
printf("%d %d",res1,res2);
return 0;

}


Time  Complexity=O(n)
Space Complexity=O(n)












-

Q. Finding integer square root of an element N (we are doing here it by 3 methods)

METHOD  1 (Naive)

It  is  naive  method  which  is  in  your  mind  in  which  we  check  every  value  from  1  to n    square  its  value  to  check  it  equal  to  N

PseudoCode

for(int i=0 to N)
{
if(i*i==N)
print  i  is  the  square  root

if(i*i>N)
print  Square  root  is  not  integer
}

Time =O(n)

METHOD  2 (Newton Raphson)

It  is  Newton - Raphson  method  as  we  can  see  that  sum  of  N  odd  terns  result  into  N^2

It  says  that  the  N consecutive  odd  elements  add  upto  give  N^2  as  its  result  as  we  can  see


1+3=4(i.e  2^2)    [2  consecutive  odd  elements  add  upto  give  4 i.e  2^2]

1+3+5+7+9+11=36(i.e  6^2)   [6  consecutive  odd  elements  add  upto  give  36 i.e  6^6]

The  programmers  having  some  knowledge  of  Mathematics  will  work  that  out  also



#include<stdio.h>

int square(int);

int square(int a)
{
int sum=0;
for(int k=0;k<a;k++)
sum+=2*k+1;
return sum;
}

int main()
{
int N;
printf("Enter  the  value  of  N");
scanf("%d",&N);
for(int k=1;k<N;k++)
{
if(square(k)==N)
{printf("%d is our answer",k);return 0;}
}
printf("No integer value is found");
return 0;
}

Time=O( sqrt(N) );




METHOD  3 (Binary  Search)

It  will  be  the  most  expected  answer  as  of  having  less  complexity  than  above


  low=0; high=N;
while
{
 mid=(low+high)/2;
if(mid*mid>N)
high=mid;
if(mid*mid==N)
done;
if(mid*mid<N)
low=mid;
if(low==high)
break;
}
print  no  result

Time=O(log n)

This  can  be  extended  for  finding  square  root  in  decimals  also

See  this  http://ideone.com/ePF12g  for  the  result

Please  tell  any  queries.......






Monday, October 14, 2013

Q. Find the maximum difference between two elements i and j a[i] -a[j] where j>i

Example:
{1,23,56,24,76,89,123,32,47,94}
a[i]=123  and  a[j]=32
answer  is  123 - 32= 91
(see  -122  will  not  be  answer  here  we  dont  have  to  calculate  absolute  one... )
METHOD 1

A  completely  naive  method  in  which  for  every  element  we  calculate  difference  with  the  left  out  elements  and  maintain  the  maximum  difference.  This  method  will  not  be  expected  in  interviews .

for(i=0 to n)
{
for(j=i to n)
result=compute a[i]-a[j]
if(result>maxYet)
maxYet=result;
}

#include<stdio.h>
int main()
{
int result=0;
int arr[10]={1,23,56,24,76,89,123,32,47,94};
int minNumber=arr[9];
int maxResult=0;
for(int k=9;k>=0;k--)
{
for(int k1=9;k1>=k;k1--)
{
int diff=arr[k]-arr[k1];
if(result<diff)
result=diff;
}
}
printf("%d",result);
return 0;
}


Space  Complexity=O(1)
Time   Complexity=O(n^2)

METHOD 2

One  scan  method  for  this   is  to  scan  the  elements  from  right  only  and  calculate 
result= a[i]-min(a[i+1....n])
maximum  of  result  is  our  answer

max=0;
for(j=n  to  0)
{
result= a[j]-min(a[j  to  n])
if(max<result)
result=max;
}


#include<stdio.h>
int main()
{
int arr[10]={1,23,56,24,76,89,123,32,47,94};
int minNumber=arr[9];
int maxResult=0;
for(int k=9;k>=0;k--)
{
if(minNumber>arr[k])
minNumber=arr[k];
int result=arr[k]-minNumber;
if(result>maxResult)
maxResult=result;
}
printf("%d",maxResult);
return 0;
}


Space  Complexity=O(1)
Time  Complexity=O(n)

Saturday, October 12, 2013

Q. Spiral Traversal of a nxn matrix where n is odd..

Well  this  is  a  really  good  question  for  your  coding  practice. This  is asked  in  many  interviews  to  check  the  coding  abilities  of  the  candidiates

Lets  have  a  5x5  matrix  as  an  example


0 1 2 3 4

5 6 7 8 9

10 11 12 13 14

15 16 17 18 19

20 21 22 23 24



for  this  answer  should  be
0 1 2 3 4 9 14 19 24 23 22 21 20 15 10 5 6 7 8 13 18 17 16 11 12

Time  Complexity=O(n)
Space Complexity=O(1)


#include<stdio.h>

int main()
{
int n=5;
int arr[n][n];
int top=0,bottom=n,left=0,right=n;//these  are  the  boundaries  of  the  matrix  while  traversing  spirally
int currX=0,currY=0;//these  are  the  locations  which  are  being  traversed

//arr  is  having  value  0 to 48  in  row  majority  order
for(int k=0;k<n;k++)
for(int k1=0;k1<n;k1++)
arr[k][k1]=n*k+k1;

// this is for printing matrix value
/*for(int k=0;k<n;k++)
{
for(int k1=0;k1<n;k1++)
printf("%d\t",arr[k][k1]);
printf("\n");
}*/


while((currX!=n/2)&&(currY!=n/2))
{
//printf("%d %d %d %d\n",left,right,top,bottom);
while(currX<right)
{printf("%d\t",arr[currY][currX]);currX++;}right--;currX--;currY++;top++;

while(currY<bottom)
{printf("%d\t",arr[currY][currX]);currY++;}bottom--;currY--;currX--;

while(currX>=left)
{printf("%d\t",arr[currY][currX]);currX--;}left++;currX++;currY--;

while(currY>=top)
{printf("%d\t",arr[currY][currX]);currY--;}currY++;currX++;
}
printf("%d",arr[n/2][n/2]);
return 0;
}

Thursday, October 10, 2013

Q. Given an array of size n. It contains numbers in the range 1 to n. Each number is present at least once except for 2 numbers (one is missing and one is repeated)

INPUT               {2,1,3,3,5}  n=5
Missing  one  is  4  and  repeating  one  is  3


It  means  that  one  number  is  missing  and  other  is  repeating  twice  and  we  have  to  find  both  of  them..

METHOD  1

It  is  the  most  obvious  way  to  do  this  which  is  to  sort  them  first  and  then  we  may  be  easily  able to  find  the  remaining  ones...

Time Complexity=O(n logn),,for   merge  sort
Space Complexity=O(n), for  stack  used  in  merge  sort 

METHOD  2

Hash  the  above  elements  and  store  count  as their  values  and  we  may  easily  get  the  answer

METHOD 3

It  is  a  little  tricky  as  it  involves  two  equations  in  this

sum(n)=n(n+1)/2,,
product  of  n=n!

now in  our  given  array  we  will  be  having  sum  as  (sum+repeated-missed)

and  similarly  we  will  have  our  product  as  (product*repeated)/missed

And  hence  we   get  our  two  equations  to  be  solved

Sunday, October 6, 2013

Q. Position all elements less than 0 before elements greater than 0

INPUT                     6, -1, -2, 2, -4, 3, 5
OUTPUT                 -4, -2,-1  2 ,6 ,3 ,5



This  is  a  very  common  question  asked  in  which  can  be  of  form  arranging  all  even  numbers  before than  odd  ones  or  keeping  all  0  values  before  1 etc....  And  they  always  expect  you  to  solve  in  one  scan  and  in  place...


METHOD 1

In  this  we  take  another  array  of  same  size  and  first  push  all  the  negative  elements  and  then  in  second  scan  er  push  all  positive  elements..

Time  Complexity= O(n)
Space COmplexity=O(n)

METHOD 2

We  take  two  pointers  ptr1  and  ptr2.

ptr1  points  to  first  occurence  of  positive  elements,,

and  ptr2  searches  the  negative  number  to  the  right  of  ptr1  if  we  do  not  find  any  -ve  number  we  break...

else  we  we  swap  them  and  find  our  new  ptr1  which  is  obviously  greater  than  the  previous  value


#include<stdio.h>
void swap(int*,int,int);
void swap(int *arr,int ptr1,int ptr2)
{
int temp=arr[ptr1];
arr[ptr1]=arr[ptr2];
arr[ptr2]=temp; }

int main()
{
int bbreak=true;
int arr[7]={6, -1, -2, 2, -4, 3, 5};
int ptr1=-1,ptr2=-1;
//ptr1 maintains  the  first  +ve  element
while(1)
{
for(int k=ptr1;k<7;k++)
if(arr[k]>0)
{ptr1=k;break;}
for(int k=ptr1;k<7;k++)
{
if(arr[k]<0)
{swap(arr,ptr1,k);bbreak=false;}
}
if(bbreak==true)
break;
bbreak=true;
}
for(int k=0;k<7;k++)
printf("%d\t",arr[k]);
}

Saturday, October 5, 2013

Q. Generate the next pallindrome number from a given 5 digit number

e.g
INPUT          36067

OUTUT        36163




METHOD

This  question  can  be  generalized  to  any  odd  number  digit  and  is  very  easy  and  mathematical  and  a  good  coding  question  too..

Well  I  am  not  able  to  find  any  other  method  for  this  question.

Take  the  number  in  an  array.....

int a[]=| 3 | 6 | 0 | 6 | 7 |

int  mid=a[2]=0

well  now  we  have  to  check  if  reverse  of  a[0..1]i.e  63  and  a[3...4]i.e  67,,

which  of  them  is  larger.. in  this  case  67

if  a[3...4]  is  larger,,  mid++;  And  our  example  belongs  to  this  case  so  0  becomes  1
else do  nothing...

now  just  reverse  the  a[0..1]  and  put  in  place  of  a[3...4]....  to  get  36163....



#include<stdio.h>


int main()

{

int n=36967;

int temp=n;

int mid=2;

int arr[5];

for(int k=4;k>=0;k--)

{

arr[k]=temp%10;

temp=temp/10;

}

//now compare  mid-1 and  mid+1  and  so  on......

for(int k=1;k<3;k++)

{

if(arr[mid-k]>arr[mid+k])

break;

else if(arr[mid+k]>arr[mid-k])

{

if(arr[mid]!=9)

arr[mid]++;

else

{arr[mid]=0;arr[mid-1]++;}

break;

}

else

continue;

}


     //  now  reverse  1st  part  and  2nd  part

     

     for(int k=1;k<3;k++)

     {

      arr[mid+k]=arr[mid-k];

     }


for(int k=0;k<5;k++)

printf("%d",arr[k]);

return 0;

}

 Hope  you  understood  everything..  And  please  tell  me  if  you  find  any  test  case  not  working
Any  suggestions  are  welcomed..


Thursday, October 3, 2013

Q. Generate a number just immediate to the given number where generated number is the permutation of digits of the number.


  e.g
 INPUT               1234  
OUTPUT            1243    
   
  INPUT               65  
 OUTPUT            No  such  number  exists


 INPUT                345576
 OUTPUT             345657


 METHOD 1


A  very  naive  method  is  to  form  all  permutations  and  then  find  the  next  immediate  successor. It  is  highly  not  recommended  as  then  it  will  take  only  few  seconds  for  you  to  get  disqualified

METHOD 2

Yeah,  a  method  in  which  you  store  every  element  in  an  array  like
e.g   345576
a=  | 3 | 4 | 5 | 5 | 7 | 6 |

Now  you  take  the  last  element i.e 6  and  then  compare  it  with  7,5,5,4,3  to  find  the  first  minimum  which  is  5

and  then  swap  6  and  5  to  form

a=  | 3 | 4 | 5 | 6 | 7 | 5 |

Now  we  have  to  sort  the  array  from  positions  1  to  0  in  ascending  order

that  is  a=  | 3 | 4 | 5 | 6 | 5 | 7 |

For  sorting,,
we  are  opting  count  sort

We  have  to  keep  the  count[10]  of  size  10  where  index  is  the  key  and  count  is  its  value.  

Basic  funda  was  to  replace  a  digit  having  low  weight(unit place or tens...) but greater  than  any  digit  which  is  less  in  magnitude   but  is  having  higher weight  than  that.

Time  Complexity=O(n^2)
Space Complexity=O(n)

#include<stdio.h>

int main()

{

int n=48298;

int bresult=0;

int length=0;

int temp=n;

int hash[10]={0,0,0,0,0,0,0,0,0,0};

int mark;

int result=0;

int numarr[10];

for(int k=0;k<10;k++)

numarr[k]=11;

for(int k=0;k<10;k++)

{

if(temp==0)

break;

numarr[k]=temp%10;

temp=temp/10;

length++;

}

for(int k=0;k<=length-1;k++)

{

for(int i=k+1;i<=length;i++)

{

if(numarr[i]<numarr[k])

{

bresult=1;mark=i;

//swap k and mark

int stemp=numarr[k];

numarr[k]=numarr[mark];

numarr[mark]=stemp;

for(int k1=0;k1<mark;k1++)

hash[numarr[k1]]++;

break;

}

}

if(bresult==1)

break;

}

if(bresult==1)

{

int k2=0;

for(int k1=9;k1>=0;k1--)

{

if(hash[k1]>0)

{

while(hash[k1]>0)

{

numarr[k2++]=k1;

hash[k1]--;

}

}

}

for(int k1=9;k1>=0;k1--)

{

if(numarr[k1]==11)

continue;

else

{

result=10*result+numarr[k1];

}

}

printf("%d",result);

}

if(bresult==0)

printf("No value is found");

return 0;

}


Hope  you  all  find  it  useful. Please  inform  me  when  you  find  anything  challenging  to  understand  or  you  want  to  provide  me  suggestions  for  improvement.

Thanks  for  all  your  support