How to Efficiently Merge Two Sorted Arrays in TypeScript Without Extra Memory Allocation?
I'm currently working on a TypeScript project where I need to merge two sorted arrays into a single sorted array. I want to do this without creating additional memory for the merged array, as the inputs can be quite large, and performance is critical. I've attempted to use the two-pointer technique to traverse both arrays, but I'm running into issues with handling edge cases where one of the arrays might be empty or contain all larger/smaller elements than the other. Hereโs the code I've written so far: ```typescript function mergeSortedArrays(arr1: number[], arr2: number[]): number[] { const merged: number[] = []; let i = 0, j = 0; while (i < arr1.length && j < arr2.length) { if (arr1[i] < arr2[j]) { merged.push(arr1[i]); i++; } else { merged.push(arr2[j]); j++; } } // Handle remaining elements while (i < arr1.length) { merged.push(arr1[i]); i++; } while (j < arr2.length) { merged.push(arr2[j]); j++; } return merged; } ``` When I call this function with two sorted arrays, like so: ```typescript const result = mergeSortedArrays([1, 3, 5], [2, 4, 6]); console.log(result); // Expected output: [1, 2, 3, 4, 5, 6] ``` It works perfectly for regular cases, but when I try something like: ```typescript const result = mergeSortedArrays([], [2, 4, 6]); console.log(result); // Expected output: [2, 4, 6] ``` It also works, but Iโm concerned about the performance when both arrays are large and particularly when they are completely disjoint. I'm also unsure if this method is the most efficient way to merge these arrays without using extra space for the merged result. In scenarios where the input arrays can be very large, I'm worried about the time complexity and memory footprint. Is there a more optimal approach to achieve this?