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 = arr1.Length, m = arr2.Length;
for (int i = 0; i < n; i++) {
if (arr1[i] > arr2[0]) {
int temp = arr1[i];
arr1[i] = arr2[0];
arr2[0] = temp;
// Re-sort arr2's first element to correct position
int first = arr2[0], k;
for (k = 1; k < m && arr2[k] < first; k++) {
arr2[k - 1] = arr2[k];
}
arr2[k - 1] = first;
}
}
}
This code merges two sorted arrays by swapping elements and keeping the second array sorted without extra space.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Outer loop runs through all elements of the first array.
- Nested operation: Inner loop shifts elements in the second array to keep it sorted after each swap.
- How many times: Outer loop runs n times; inner loop can run up to m times in worst case.
As the arrays get bigger, the number of operations grows roughly by multiplying their sizes.
| Input Size (n, m) | Approx. Operations |
|---|---|
| 10, 10 | Up to 100 |
| 100, 100 | Up to 10,000 |
| 1000, 1000 | Up to 1,000,000 |
Pattern observation: Doubling the size roughly squares the number of operations.
Time Complexity: O(n * m)
This means the time needed grows proportionally to the product of the sizes of the two arrays.
[X] Wrong: "Since both arrays are sorted, merging without extra space is always O(n + m)."
[OK] Correct: The inner shifting loop can run many times, making the total steps multiply, not just add.
Understanding this helps you explain trade-offs between space and time, a key skill in coding interviews.
"What if we used a gap method to compare and swap elements instead? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem requirement
The task is to merge two sorted arrays so that the combined elements remain sorted, but without using any extra space like a new array.Step 2: Identify the correct approach
We must rearrange elements within the given arrays themselves to maintain sorted order without additional memory.Final Answer:
Combine both arrays into one sorted sequence without using extra memory -> Option BQuick Check:
Merge without extra space = Combine in place [OK]
- Assuming extra space is allowed
- Sorting arrays separately without merging
- Creating a new array for merged result
Solution
Step 1: Check swapping logic correctness
if (arr1[i] > arr2[j]) { int temp = arr1[i]; arr1[i] = arr2[j]; arr2[j] = temp; } uses a temporary variable to swap values correctly without losing data.Step 2: Analyze other options for errors
arr1[i] = arr2[j]; arr2[j] = arr1[i]; overwrites arr2[j] before saving arr1[i], losing original value. arr1[i] = arr1[i] + arr2[j]; arr2[j] = arr1[i] - arr2[j]; arr1[i] = arr1[i] - arr2[j]; uses arithmetic swap but can cause overflow and is less safe. int temp = arr2[j]; arr2[j] = arr1[i]; arr1[i] = temp + 1; incorrectly adds 1 during swap, changing values.Final Answer:
if (arr1[i] > arr2[j]) { int temp = arr1[i]; arr1[i] = arr2[j]; arr2[j] = temp; } -> Option CQuick Check:
Temporary variable swap = Correct swap [OK]
- Overwriting values without temp variable
- Using unsafe arithmetic swaps
- Altering values unintentionally during swap
int[] arr1 = {1, 5, 9, 10, 15, 20};
int[] arr2 = {2, 3, 8, 13};
int n = arr1.Length, m = arr2.Length;
for (int i = 0; i < n; i++) {
if (arr1[i] > arr2[0]) {
int temp = arr1[i];
arr1[i] = arr2[0];
arr2[0] = temp;
int first = arr2[0];
int k;
for (k = 1; k < m && arr2[k] < first; k++) {
arr2[k - 1] = arr2[k];
}
arr2[k - 1] = first;
}
}Solution
Step 1: Trace the swapping and insertion in arr2
For each element in arr1, if it is greater than arr2[0], swap and then insert arr2[0] in sorted order in arr2. This pushes larger elements to arr2.Step 2: Final arrays after all iterations
After all swaps and insertions, arr1 becomes [1, 2, 3, 5, 8, 9] and arr2 becomes [10, 13, 15, 20].Final Answer:
arr1 = [1, 2, 3, 5, 8, 9], arr2 = [10, 13, 15, 20] -> Option DQuick Check:
In-place merge with insertion sort = arr1 and arr2 sorted [OK]
- Not inserting arr2[0] correctly after swap
- Overwriting arr2 elements incorrectly
- Confusing array indices during insertion
for (int i = 0; i < n; i++) {
if (arr1[i] > arr2[0]) {
int temp = arr1[i];
arr1[i] = arr2[0];
arr2[0] = temp;
int first = arr2[0];
int k = 1;
while (k < m && arr2[k] < first) {
arr2[k - 1] = arr2[k];
k++;
}
arr2[k] = first;
}
}Solution
Step 1: Analyze insertion logic in arr2
The code shifts elements left to make space for 'first'. The correct insertion index after shifting is k - 1, not k.Step 2: Identify the error impact
Assigning arr2[k] = first overwrites the next element incorrectly, causing wrong order.Final Answer:
The insertion index in arr2 is incorrect; should be arr2[k - 1] = first -> Option AQuick Check:
Correct insertion index = k - 1 [OK]
- Using wrong index for insertion after shifting
- Incorrect swap logic
- Wrong loop start index
arr1 = [1, 4, 7, 8, 10]arr2 = [2, 3, 9]How would you merge them without extra space so that after merging,
arr1 contains the first 5 smallest elements and arr2 contains the remaining sorted elements? Choose the correct final arrays.Solution
Step 1: Compare and swap elements between arr1 and arr2
Start from beginning of arr1, if arr1[i] > arr2[0], swap and then insert arr2[0] in sorted order in arr2.Step 2: After all swaps and insertions
arr1 becomes [1, 2, 3, 4, 7] and arr2 becomes [8, 9, 10], maintaining sorted order without extra space.Final Answer:
arr1 = [1, 2, 3, 4, 7], arr2 = [8, 9, 10] -> Option AQuick Check:
In-place merge keeps first array smallest elements [OK]
- Not maintaining sorted order after swap
- Incorrect insertion in second array
- Assuming extra space is allowed
Ready to prove it?
Pass the test and this pattern moves unknown
