how to merge two sorted integer array in place using On time and O1 space cost
Data Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.
Merging two sorted integer arrays in place using time and space is a common problem that comes up in various computer science applications. While the traditional approach of merging involves using additional space to store the merged arrays, it is possible to do it in place, thereby keeping the space complexity constant. This article explores in depth the technique to achieve this.
Problem Statement
You are given two sorted integer arrays `arr1` and `arr2`, where `arr1` has sufficient space at the end to accommodate the elements of `arr2`. The goal is to merge these arrays in a way that results in a single sorted array contained within `arr1`, using time and additional space.
Prerequisites
- Arrays: Understanding of basic array operations.
- In-Place Operations: Understanding how to manipulate elements in arrays without using additional storage.
- Sorting Algorithms: Familiarity with basic sorting principles.
Algorithm Explanation
The essence of the in-place merge algorithm is to use the existing space at the end of `arr1` to accommodate all elements. This algorithm functions by iterating backward through `arr1` and `arr2`, placing the largest element in the correct position from the end of `arr1`.
Steps to Merge
- Initialization:
- Let `m` be the number of elements initially present in `arr1` (excluding extra space).
- Let `n` be the number of elements in `arr2`.
- Set `i = m - 1` to point to the last valid element in `arr1`.
- Set `j = n - 1` to point to the last element of `arr2`.
- Set `k = m + n - 1` to point to the last position in `arr1`.
- Iteration:
- While `j >= 0`:
- Compare elements `arr1[i]` and `arr2[j]`.
- Place the greater of the two in `arr1[k]`.
- Move the appropriate index (`i`, `j`, or both) and decrement `k`.
- If any elements remain in `arr2`, copy them to `arr1`. This step is necessary because all remaining elements in `arr1` are already in place.
- Time Complexity: The entire process involves a single iteration over the two arrays, making the time complexity .
- Space Complexity: The algorithm uses no additional space apart from variables used for indices, hence .
Example
Consider the following example for clarity:
- `arr1 = [1, 3, 5, 0, 0, 0]` and `arr2 = [2, 4, 6]`
- Initial indices: `i = 2`, `j = 2`, `k = 5`
Merge Process:
| Steps | arr1 Content | i | j | k |
| Start | [1, 3, 5, 0, 0, 0] | 2 | 2 | 5 |
arr1\[2] \< arr2\[2] | [1, 3, 5, 0, 0, 6] | 2 | 1 | 4 |
arr1\[2] > arr2\[1] | [1, 3, 5, 0, 5, 6] | 1 | 1 | 3 |
arr1\[1] \< arr2\[1] | [1, 3, 5, 4, 5, 6] | 1 | 0 | 2 |
arr1\[1] > arr2\[0] | [1, 3, 3, 4, 5, 6] | 0 | 0 | 1 |
arr1\[0] \< arr2\[0] | [1, 2, 3, 4, 5, 6] | 0 | -1 | 0 |
Edge Cases
- Empty `arr2`: If `arr2` is empty, `arr1` remains unchanged.
- Empty `arr1` (besides extra space): All elements of `arr2` must be directly copied to the front of `arr1`.
- Identical Elements: Handles duplicates by merging them in sequence.
Conclusion
Merging two sorted arrays in place without using extra space is both efficient and essential for working within memory constraints. This algorithm can be extended to similar data merging problems, allowing for effective data processing with minimal overhead. This straightforward yet elegant solution showcases the powerful combination of algorithmic analysis and optimal space usage.
Related reading
- How to minimize visual width of binary search tree?
- How to modify dijkstra algorithm to find all possible paths?
- How to modify Levenshteins Edit Distance to count adjacent letter exchanges as 1 edit
- How to move duplicates to the end of an array while preserving order in C?
- How to modify a KeyValuePair value?
- How to modify list entries during for loop?
- How to minimize latency in a Kafka Streams application?
- How to minimize the latency involved in kafka messaging framework?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.