Merge Two Sorted Arrays Without Extra Space in Python

Merge two sorted arrays in-place from the end, using the trailing zeros in the first array to avoid extra space.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 15 views 0 copies

Python code

18 lines
Python 3.9+
def merge_sorted(arr1, arr2):
    m, n = len(arr1), len(arr2)
    i, j = m - 1, n - 1
    while j >= 0:
        if i >= 0 and arr1[i] > arr2[j]:
            arr1[i + j + 1] = arr1[i]
            i -= 1
        else:
            arr1[i + j + 1] = arr2[j]
            j -= 1
    return arr1


if __name__ == "__main__":
    arr1 = [1, 3, 5, 7, 0, 0, 0]
    arr2 = [2, 4, 6]
    merged = merge_sorted(arr1, arr2)
    print(merged)

Output

stdout
[1, 2, 3, 4, 5, 6, 7]

How it works

The algorithm starts from the back of both arrays, comparing the largest remaining elements and placing the larger one at the end of the merged region. The index for the placement is calculated as i + j + 1, which accounts for the current positions in both arrays. This approach works because the first array has enough trailing zeros to hold all elements of the second array. The time complexity is O(m+n) and the space complexity is O(1).

Common mistakes

  • Forgetting to account for the trailing zeros when calculating the placement index
  • Not handling the case where one array is exhausted correctly
  • Using a naive merge that overwrites values before they are read

Variations

  1. Use a similar back-to-front approach when merging two sorted linked lists in-place
  2. Implement the same logic as a LeetCode-style solution for 'Merge Sorted Array'

Real-world use cases

  • Merging two sorted time-series data streams into a single time-ordered array without allocating a new buffer.
  • Combining sorted log entries from two sources directly into a fixed-size output array in memory-constrained systems.
  • Implementing an in-place merge as part of a custom sorting algorithm like merge sort for large arrays on limited hardware.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.