Katkat

Merge two sorted arrays in-place

AmazonSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to manipulate arrays in-place while managing constraints to avoid unnecessary data movement or auxiliary space usage.

Problem Statement

You are given two sorted integer arrays arr1 and arr2, where arr1 has a size of m + n and arr2 has a size of n. The first m elements of arr1 represent the initialized elements that need to be merged with the n elements of arr2.

Your task is to merge arr2 into arr1 as a single sorted array. You must perform this operation in-place within arr1. You may assume that arr1 has enough space (size equal to m + n) to hold the elements from arr2.

Function Signature

def merge_arrays(arr1, m, arr2, n):
    """
    :type arr1: List[int]
    :type m: int
    :type arr2: List[int]
    :type n: int
    :rtype: None (Modify arr1 in-place)
    """

Examples

Example 1: Input: arr1 = [1, 3, 5, 0, 0, 0], m = 3, arr2 = [2, 4, 6], n = 3 Output: arr1 = [1, 2, 3, 4, 5, 6]

Example 2: Input: arr1 = [1, 2, 3], m = 3, arr2 = [], n = 0 Output: arr1 = [1, 2, 3]

Constraints

  • arr1.length == m + n
  • arr2.length == n
  • 0 <= m, n <= 200
  • 10^9 <= arr1[i], arr2[j] <= 10^9

Edge Cases

  • One of the arrays is empty.
  • All elements in arr2 are smaller than the smallest element in arr1.
  • All elements in arr2 are larger than the largest element in arr1.

Hints

Hint 1

Consider starting from the end of the arrays rather than the beginning to avoid overwriting elements in arr1.

Hint 2

Use three pointers: one for the end of the initialized portion of arr1, one for the end of arr2, and one for the very end of arr1.

Hint 3

If you move from the back, compare the elements at the current pointers and place the larger one at the back-most available position in arr1.

Follow-up questions

  • How would your approach change if the arrays were sorted in descending order instead of ascending?
  • What is the time and space complexity of your solution, and can you explain why it is optimal?
  • How would you handle the situation if arr1 did not have enough space and you were required to return a new merged array?