Merge Two Sorted Arrays Without Extra Space in DSA C++ - Time & Space Complexity
We want to understand how long it takes to merge two sorted arrays without using extra space.
How does the time needed grow as the arrays get bigger?
Analyze the time complexity of the following code snippet.
void merge(int arr1[], int arr2[], int n, int m) {
int i = 0, j = 0, k = n - 1;
while (i <= k && j < m) {
if (arr1[i] <= arr2[j]) {
i++;
} else {
std::swap(arr2[j++], arr1[k--]);
}
}
std::sort(arr1, arr1 + n);
std::sort(arr2, arr2 + m);
}
This code merges two sorted arrays by swapping elements and then sorting each array again.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that compares and swaps elements.
- How many times: Up to n + m times combined, since i and j move through the arrays.
- Secondary operations: Two sorting calls on arrays of sizes n and m.
As the arrays get bigger, the number of comparisons and swaps grows, plus the sorting time.
| Input Size (n + m) | Approx. Operations |
|---|---|
| 10 | About 10 comparisons + sorting small arrays |
| 100 | About 100 comparisons + sorting arrays of size n and m |
| 1000 | About 1000 comparisons + sorting arrays of size n and m |
Pattern observation: The sorting steps dominate and grow faster than the initial swaps.
Time Complexity: O((n + m) log (n + m))
This means the time grows roughly proportional to the total size times the log of the total size, mainly due to sorting.
[X] Wrong: "Swapping elements alone makes the merge operation fast and linear."
[OK] Correct: Because after swapping, sorting is still needed, which takes more time than just swapping.
Understanding this helps you explain trade-offs between using extra space and time, a common topic in interviews.
"What if we used a gap method to merge without sorting at the end? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem requirement
The problem asks to merge two sorted arrays into a single sorted sequence without using extra space, meaning no additional arrays or large buffers.Step 2: Identify the correct approach
We must rearrange elements within the given arrays to maintain sorted order combined, without allocating new memory.Final Answer:
Combine both arrays into one sorted array without using extra memory -> Option DQuick Check:
Merge without extra space = Combine in-place [OK]
- Assuming extra space is allowed
- Trying to merge by creating a new array
- Sorting arrays separately without merging
Solution
Step 1: Analyze swapping without extra variable
a = a + b; b = a - b; a = a - b; uses arithmetic operations to swap values without a temporary variable.Step 2: Check correctness of each option
temp = a; a = b; b = temp; uses a temporary variable, so it uses extra space. a = b; b = a; assigns a to b and then b to a, which loses original value. a = a * b; b = a / b; a = a / b; uses multiplication/division which can cause overflow or errors if b is zero.Final Answer:
a = a + b; b = a - b; a = a - b; -> Option AQuick Check:
Swap without temp = arithmetic trick [OK]
- Using a temporary variable (extra space)
- Overwriting values without saving
- Using multiplication/division causing errors
arr1 and arr2 after merging without extra space using the gap method?arr1 = {1, 5, 9, 10}
arr2 = {2, 3, 8, 13}Solution
Step 1: Apply gap method to merge arrays
Start with gap = ceil((4+4)/2) = 4. Compare elements at gap distance and swap if needed, then reduce gap until 0.Step 2: Final sorted arrays after gap method
After applying the method, arr1 becomes {1, 2, 3, 5} and arr2 becomes {8, 9, 10, 13}.Final Answer:
arr1 = {1, 2, 3, 5}, arr2 = {8, 9, 10, 13} -> Option AQuick Check:
Gap method merges arrays in-place correctly [OK]
- Not reducing gap properly
- Swapping wrong elements
- Confusing array indices across two arrays
for (int i = 0; i < n; i++) {
if (arr1[i] > arr2[0]) {
swap(arr1[i], arr2[0]);
sort(arr2, arr2 + m);
}
}Solution
Step 1: Analyze the loop and sorting inside it
The code sorts arr2 inside the loop for every swap, which is inefficient and increases time complexity to O(n*m*log m).Step 2: Identify the performance issue
Sorting arr2 repeatedly is costly; better methods avoid sorting inside the loop.Final Answer:
Sorting arr2 inside the loop causes high time complexity -> Option CQuick Check:
Sorting inside loop = inefficient [OK]
- Ignoring time complexity impact
- Assuming swap causes runtime error
- Confusing loop bounds
arr1 = {10, 12, 15, 18} and arr2 = {2, 5, 20, 25}, how can you merge them without extra space so that after merging, arr1 contains the first four smallest elements and arr2 contains the remaining elements sorted?Solution
Step 1: Understand the gap method for merging
The gap method reduces the gap between compared elements and swaps if needed, working across both arrays without extra space.Step 2: Apply gap method to given arrays
By repeatedly comparing and swapping elements at the gap distance, arr1 will hold the smallest elements and arr2 the larger ones, both sorted.Final Answer:
Use the gap method to compare and swap elements across arrays until fully merged -> Option BQuick Check:
Gap method merges sorted arrays in-place [OK]
- Using extra arrays violating constraints
- Sorting arrays separately without merging
- Swapping without sorting arr2 leads to wrong order
Ready to prove it?
Pass the test and this pattern moves unknown
