Merge Two Sorted Arrays Without Extra Space in DSA Java - Time & Space Complexity
When merging two sorted arrays without using extra space, it is important to know how the time taken grows as the arrays get bigger.
We want to find out how many steps the merging process takes as the input size increases.
Analyze the time complexity of the following code snippet.
public void merge(int[] arr1, int[] arr2) {
int n = arr1.length;
int m = arr2.length;
int i = 0, j = 0;
while (i < n) {
if (arr1[i] > arr2[0]) {
int temp = arr1[i];
arr1[i] = arr2[0];
arr2[0] = temp;
// Re-sort arr2's first element
int first = arr2[0];
int k = 1;
while (k < m && arr2[k] < first) {
arr2[k - 1] = arr2[k];
k++;
}
arr2[k - 1] = first;
}
i++;
}
}
This code merges two sorted arrays by swapping elements and re-sorting the second array's first element without extra space.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The outer while loop runs through all elements of the first array.
- Nested operation: The inner while loop shifts elements in the second array to keep it sorted after swapping.
- How many times: Outer loop runs n times; inner loop can run up to m times in worst case.
As the size of the arrays grows, the number of operations increases because for each element in the first array, we might shift many elements in the second array.
| Input Size (n, m) | Approx. Operations |
|---|---|
| 10 | Up to 10 * 10 = 100 |
| 100 | Up to 100 * 100 = 10,000 |
| 1000 | Up to 1000 * 1000 = 1,000,000 |
Pattern observation: The operations grow roughly by the square of the input size, meaning doubling the size makes the work about four times bigger.
Time Complexity: O(n * m)
This means the time taken grows proportionally to the product of the sizes of the two arrays.
[X] Wrong: "Since both arrays are sorted, merging without extra space should be just O(n + m)."
[OK] Correct: The inner shifting loop in the second array can cause many moves, making the process slower than a simple linear pass.
Understanding this time complexity helps you explain trade-offs when merging arrays without extra space, a common real-world problem where memory is limited.
"What if we used a gap method to reduce the number of shifts? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem requirement
The problem asks to merge two sorted arrays into a sorted sequence without using extra space, meaning no additional arrays or large memory allocation.Step 2: Identify the correct approach
Using in-place techniques like swapping elements between arrays and sorting them ensures no extra space is used.Final Answer:
Combine both arrays into one sorted sequence without using extra memory -> Option AQuick Check:
Merge without extra space = Combine in-place [OK]
- Thinking extra array is allowed
- Sorting arrays separately without merging
- Using extra memory for temporary storage
arr1 and arr2 at indices i and j without extra space?Solution
Step 1: Check the swap logic
Swapping requires a temporary variable to hold one value while assigning the other to avoid overwriting.Step 2: Verify correct use of temp variable
int temp = arr1[i]; arr1[i] = arr2[j]; arr2[j] = temp; uses a temp variable to hold arr1[i], then assigns arr2[j] to arr1[i], and finally assigns temp to arr2[j], correctly swapping values.Final Answer:
int temp = arr1[i]; arr1[i] = arr2[j]; arr2[j] = temp; -> Option DQuick Check:
Swap needs temp variable = int temp = arr1[i]; arr1[i] = arr2[j]; arr2[j] = temp; [OK]
- Assigning without temp causes overwriting
- Swapping elements within the same array incorrectly
- Confusing indices during swap
arr1 = [1, 5, 9, 10] and arr2 = [2, 3, 8, 13], after applying the merge without extra space algorithm, what will be the final state of arr1 and arr2?Solution
Step 1: Compare and swap elements between arrays
Start comparing last element of arr1 with first of arr2. Swap if arr1 element is greater. After swaps, sort both arrays.Step 2: Final sorted arrays after merging
After swapping and sorting, 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 BQuick Check:
In-place merge sorts arrays = arr1 = [1, 2, 3, 5], arr2 = [8, 9, 10, 13] [OK]
- Not sorting arrays after swapping
- Swapping incorrectly leading to unsorted arrays
- Mixing indices during swaps
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] > arr2[0]) {
int temp = arr1[i];
arr1[i] = arr2[0];
arr2[0] = temp;
Arrays.sort(arr2);
}
}Solution
Step 1: Analyze sorting inside the loop
The code sorts arr2 inside the loop every time a swap happens, which is inefficient and slows down the algorithm.Step 2: Suggest optimization
Sorting arr2 once after all swaps or using a better approach like gap method improves performance.Final Answer:
Sorting arr2 inside the loop causes unnecessary repeated sorting -> Option CQuick Check:
Repeated sorting inside loop = inefficiency [OK]
- Sorting arr2 repeatedly inside loop
- Confusing loop limits between arrays
- Ignoring performance impact of repeated sorting
arr1 = [1, 4, 7, 8, 10] and arr2 = [2, 3, 9]. Using the gap method to merge without extra space, what is the final state of both arrays?Solution
Step 1: Calculate initial gap and compare elements
Total length is 8, initial gap = ceil(8/2) = 4. Compare elements at gap distance and swap if needed, then reduce gap.Step 2: Perform gap reductions and swaps
After successive gap reductions (4, 2, 1), arrays become sorted as arr1 = [1, 2, 3, 4, 7] and arr2 = [8, 9, 10].Final Answer:
arr1 = [1, 2, 3, 4, 7], arr2 = [8, 9, 10] -> Option AQuick Check:
Gap method sorts arrays in-place = arr1 = [1, 2, 3, 4, 7], arr2 = [8, 9, 10] [OK]
- Not reducing gap correctly
- Swapping wrong elements across arrays
- Confusing gap calculation with array lengths
Ready to prove it?
Pass the test and this pattern moves unknown
