A trading app keeps two sorted price buffers that were allocated once and must not grow, shrink or be copied: memory on the device is tight. At the end of the day the two buffers must hold the combined data in order, with the smallest values in the first buffer and the rest in the second.
Write mergeInPlace(a, b, compare). a (length n) and b (length m) are each sorted in ascending order. Rearrange their elements so that, read as a followed by b, all n + m elements are in ascending order. Afterwards a holds the n smallest elements and b the m largest, both sorted.
Rules:
Modify a and bin place: keep the same array objects and the same lengths, and return undefined.
Use O(1) extra space: no copy of either array, no third array, no concatenation. The tests cannot measure memory, but an interviewer will ask.
compare(x, y) is optional and works like a sort comparator: negative when x comes first, positive when y does, 0 when equal. Without it, elements must be finite numbers compared numerically. The order of equal elements does not matter.
Throw a TypeError when a or b is not an array, compare is given but is not a function, an element is not a finite number (without compare), or either array is not sorted according to the comparator.
Each array can have 100,000 elements. Shifting a to insert each element of b is O(n × m); aim for O((n + m) log(n + m)).