Video in progress
How do you merge two sorted arrays into one sorted array?
I put one pointer on each array, write the smaller element to the result and advance that pointer. When one array runs out, I copy the rest of the other. Time is O(n + m), and no re-sorting is needed.
📖 Answer
static int[] merge(int[] a, int[] b) {
int[] res = new int[a.length + b.length];
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length) {
res[k++] = (a[i] <= b[j]) ? a[i++] : b[j++];
}
while (i < a.length) res[k++] = a[i++];
while (j < b.length) res[k++] = b[j++];
return res;
}
With <=, on equal elements the one from the first array comes first, so the sort stays stable. This function is the heart of merge sort.
Concatenating both arrays and calling Arrays.sort also gives the right result, but it's O((n+m) log(n+m)). What the interviewer is checking is exactly "do you take advantage of the fact that they're sorted?".
A well-known variant: the first array has free space at the end, and you must write the result into it in place. In that case you fill from the end, starting with the largest elements, so you don't overwrite elements you haven't read yet.
Sign up to mark studied questions and save your progress.