Merge Sorted Arrays
Problem Statement
Given two sorted integer arrays, merge them into a single sorted array. The solution should handle the arrays efficiently without using extra space beyond the output array.
Example
Input: nums1 = [1, 2, 3], nums2 = [2, 5, 6]
Output: [1, 2, 2, 3, 5, 6]
Code
Java
Python
JavaScript
public class Solution { public int[] mergeSortedArrays(int[] nums1, int[] nums2) { int[] result = new int[nums1.length + nums2.length]; int i = 0, j = 0, k = 0; while (i < nums1.length && j < nums2.length) { if (nums1[i] <= nums2[j]) { result[k++] = nums1[i++]; } else { result[k++] = nums2[j++]; } } while (i < nums1.length) { result[k++] = nums1[i++]; } while (j < nums2.length) { result[k++] = nums2[j++]; } return result; } }
def merge_sorted_arrays(nums1, nums2): result = [] i, j = 0, 0 while i < len(nums1) and j < len(nums2): if nums1[i] <= nums2[j]: result.append(nums1[i]) i += 1 else: result.append(nums2[j]) j += 1 result.extend(nums1[i:]) result.extend(nums2[j:]) return result # Example usage print(merge_sorted_arrays([1, 2, 3], [2, 5, 6]))
function mergeSortedArrays(nums1, nums2) { const result = []; let i = 0, j = 0; while (i < nums1.length && j < nums2.length) { if (nums1[i] <= nums2[j]) { result.push(nums1[i++]); } else { result.push(nums2[j++]); } } return result.concat(nums1.slice(i), nums2.slice(j)); } // Example usage console.log(mergeSortedArrays([1, 2, 3], [2, 5, 6]));
Explanation
- Use two pointers to track positions in both arrays.
- Compare elements and add the smaller one to the result.
- Move the pointer of the array from which an element was taken.
- Append remaining elements from either array, if any.
Note
Time complexity is O(n + m) where n and m are the lengths of the input arrays. Space complexity is O(n + m) for the result array.