โ† Back to Index

๐Ÿ“š Merge Sorted Array โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The problem involves merging two sorted arrays into one sorted array in-place. The first array has enough space to hold the elements of both arrays.

This is a classic two-pointer problem where we start merging from the end of the arrays to avoid overwriting elements in the first array.

๐Ÿงฑ Pattern Template

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int i = m - 1; // Pointer for nums1
        int j = n - 1; // Pointer for nums2
        int k = m + n - 1; // Pointer for the merged array

        // Merge nums1 and nums2 from the end
        while (i >= 0 && j >= 0) {
            if (nums1[i] > nums2[j]) {
                nums1[k--] = nums1[i--];
            } else {
                nums1[k--] = nums2[j--];
            }
        }

        // Copy remaining elements from nums2, if any
        while (j >= 0) {
            nums1[k--] = nums2[j--];
        }
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Merge Sorted Array

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]

Explanation:
- Start merging from the end of nums1 and nums2.
- Compare elements and place the larger one at the end of nums1.
- Continue until all elements are merged.

๐Ÿ’ก Pro Tips