Amazon Interview Question
Software Engineer / DevelopersNOTE: I am learning efficient programming(i.e.. time & space optimized code,easily understandable code).If you find any error in my below code, could you please let me know errors/suggestions in the code.
void mergingSortedArrays(int *A, int m, int *B, int n)
{
int i = m-1, j = n-1, k = m+n-1;
while( i >= 0 && j >= 0 )
{
if(B[j] >= A[i] )
{
B[k--] = B[j--] ;
}
else
{
B[k--] = A[i--] ;
}
}
while( i >= 0 )
{
B[k--] = A[i--];
}
}
Time complexity: O(n)
Space Complexity : O(1)
Merging in oposite way.
- Anurag Singh February 08, 2011Merge A and B from back to front. Get max values from A and B and put in B from back side.
for(i=X-1,j=Y-1;i>=0 && j>=0;)
{
if(A[i] >= B[j])
{
B[i+j+1]=A[i];
i--;
}
else
{
B[i+j+1]=B[j];
j--;
}
if(i>0)
{
for(k=0;k<=i;k++)
B[k]=A[k];
}
}