# Merge Sorted Array (88)

**Note:**

* **The number of elements initialized in&#x20;*****nums1*****&#x20;and&#x20;*****nums2*****&#x20;are&#x20;*****m*****&#x20;and&#x20;*****n*****&#x20;respectively.**
* **You may assume that&#x20;*****nums1*****&#x20;has enough space (size that is equal to&#x20;*****m*****&#x20;+&#x20;*****n*****) to hold additional elements from&#x20;*****nums2*****.**

```
Input:
nums1 = [5,13,17,0,0,0,0], m = 3
nums2 = [3,7,11,19],       n = 4
```

### Approach:

We cannot iterate thorugh both array on tandem as if an entry in the second array is smaller than some entry in the first array, we would have to shift all the subsequent entries in the first array by 1, potentially rendering the worst came time to `O(mn)` if every entry in array2 is smaller than each entry in array1.&#x20;

Since we have spare space at the end of the first array. We take advantage of this by filling the first array from its end. The last element in the result will be written to index `m + n - 1`. nums1 would be updated in the follwing manner

```java
nums1 = [5,13,17,0,0,0,19,0]
nums1 = [5,13,17,0,0,17,19,0]
nums1 = [5,13,17,0,13,17,19,0]
nums1 = [5,13,17,11,13,17,19,0]
nums1 = [5,13,7,11,13,17,19,0]
nums1 = [5,5,7,11,13,17,19,0]
nums1 = [3,5,7,11,13,17,19,0]
```

```java
class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int k = m + n - 1;
        int i = m - 1, j = n - 1;
        
        while(i >= 0 && j >= 0){
            nums1[k --] = nums2[j] > nums1[i] ? nums2[j--] : nums1[i--];
        }
        while(j >= 0)
            nums1[k--] = nums2[j--];
    }
}
```

**`Time: O(m + n)                Space: O(1)`**
