Google Interview Question

You are given a collection of M arrays with N integers. Every array is sorted. Develop an algorithm to combine each array into one sorted array.

Interview Answers

Anonymous

Nov 4, 2015

If merge sort is the best answer, then I think half the point might be to then ask "How long does it take?" My thinking is imagine this problem is solving a partially completed merge sort. There are M*N elements, so a standard, full merge sort would have taken O(MN log(MN)), but we have less work to do than that (if N > 1). In standard merge sort, we have MN work at each stage, each stage merging all of the small arrays together to make arrays twice as large, and there are log(MN) stages. Here, we only have log(M) stages left before we have a fully merged array, so this algorithm should take O(MN log(M)) time.

3

Anonymous

Oct 10, 2015

Two ways I came up with: One is to merge the arrays in pairs. Once all pairs are merged, merge the pairs again, repeating until there is only one array remaining. The other is to think of each array as a stack, and keep the arrays organized in a heap according to the top integer in each array.

2