JavaScriptMedium
Merge two sorted arrays
Use two pointers, one per array: repeatedly take the smaller current element into the result and advance that pointer, then append whatever remains; this produces a sorted result in O(n + m) time, which beats concatenating and re-sorting (O((n + m) log(n + m))).
Algorithm
i = 0,j = 0,result = [].- While both have elements: push
a[i] <= b[j] ? a[i++] : b[j++]. Using<=keeps the merge stable (equal elements fromacome first). - Append the remaining elements of whichever array is not exhausted.
Variations
- Custom comparator for objects (merge two lists of events by timestamp).
- Merge in place (LeetCode 88): when
ahas extra space at the end, fill from the back with three pointers so nothing is overwritten. O(1) extra space. - Remove duplicates while merging (union of sorted arrays).
- Merge k sorted arrays: use a min-heap (O(N log k)), or merge pairs repeatedly like merge sort.
- Intersection of two sorted arrays with the same two-pointer idea.
Why it matters
This is the merge step of merge sort and the basis for combining sorted streams (paginated results from two sources, log files, time-series data).
Code example
js
1function mergeSorted(a, b, compare = (x, y) => x - y) {2 const out = [];3 let i = 0, j = 0;4 while (i < a.length && j < b.length) {5 out.push(compare(a[i], b[j]) <= 0 ? a[i++] : b[j++]); // <= keeps it stable6 }7 while (i < a.length) out.push(a[i++]);8 while (j < b.length) out.push(b[j++]);9 return out;10}1112console.log(mergeSorted([1, 3, 5, 7], [2, 4, 6, 8, 10, 12])); // [1, 2, 3, 4, 5, 6, 7, 8, 10, 12]13console.log(mergeSorted([], [1, 2]), mergeSorted([5], [])); // [1, 2] [5]1415// Objects with a comparator: merge two feeds by time16const feedA = [{ t: 1, src: "A" }, { t: 4, src: "A" }];17const feedB = [{ t: 2, src: "B" }, { t: 4, src: "B" }, { t: 9, src: "B" }];18console.log(mergeSorted(feedA, feedB, (x, y) => x.t - y.t).map((e) => `${e.t}${e.src}`)); // ["1A", "2B", "4A", "4B", "9B"]1920// In place, filling from the back (LeetCode 88)21function mergeInPlace(nums1, m, nums2, n) {22 let i = m - 1, j = n - 1, k = m + n - 1;23 while (j >= 0) nums1[k--] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--];24 return nums1;25}26console.log(mergeInPlace([1, 2, 3, 0, 0, 0], 3, [2, 5, 6], 3)); // [1, 2, 2, 3, 5, 6]2728// Merge k sorted arrays by merging pairs (like merge sort)29const mergeK = (lists) => (lists.length <= 1 ? lists[0] ?? [] : mergeSorted(mergeK(lists.slice(0, lists.length >> 1)), mergeK(lists.slice(lists.length >> 1))));30console.log(mergeK([[1, 4], [2, 5], [0, 3, 6]])); // [0, 1, 2, 3, 4, 5, 6]
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.