"Suppose we have two sorted arrays A[] of m elements and B[] of n elements. Write a function merge which would merge this two arrays into new sorted array C[] in O(n) time as shown on the picture".
Company where asked this question: Amazon
Interviewed for position: Software Developers, Testers
Company where asked this question: Amazon
Interviewed for position: Software Developers, Testers
I doubt this can be done on O(n). If n.eq.1, m.gt.0, and B[0].lt.A[0], then there will have to be m assignments after assigning C[0] = B[0]. Here is my solution on O(m+n).
a=0; b=0; c=0;
while ((a.lt.m) and (b.lt.n)) do
___C[c++] = (A[a].lt.B[b]) ? A[a++] : B[b++];
while (a.lt.m) do
___C[c++] = A[a++];
while (b.lt.n) do
___C[c++] = B[b++];