Merge Two Sorted Arrays Without Extra Space in DSA Python - 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.
for i in range(len(arr1)):
if arr1[i] > arr2[0]:
arr1[i], arr2[0] = arr2[0], arr1[i]
# Re-sort arr2 to keep it sorted
first = arr2[0]
k = 1
while k < len(arr2) and arr2[k] < first:
arr2[k - 1] = arr2[k]
k += 1
arr2[k - 1] = first
This code merges two sorted arrays by swapping elements and re-sorting the second array in place.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Outer loop runs over all elements of the first array.
- How many times: For each element in the first array, a possible inner while loop re-sorts part of the second array.
As the size of the arrays grows, the outer loop runs once per element in the first array.
The inner while loop can run up to the length of the second array in the worst case.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 100 (10 * 10) |
| 100 | Up to 10,000 (100 * 100) |
| 1000 | Up to 1,000,000 (1000 * 1000) |
Pattern observation: The operations grow roughly with the product of the sizes of the two arrays, meaning it grows quickly as arrays get bigger.
Time Complexity: O(n * m)
This means the time needed grows proportionally to the size of the first array times the size of the second array.
[X] Wrong: "Since both arrays are sorted, merging without extra space is always O(n + m)."
[OK] Correct: The inner re-sorting loop can cause extra work, making the process slower than a simple linear merge.
Understanding this time complexity helps you explain trade-offs when merging arrays without extra space, a useful skill in interviews and real coding tasks.
"What if we used a gap method to merge the arrays instead? 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 new arrays can be created.Step 2: Identify the correct approach
We must rearrange elements within the given arrays to maintain sorted order without additional memory.Final Answer:
Combine both arrays into one sorted array without using extra memory -> Option AQuick Check:
Merge without extra space = Combine in-place [OK]
- Trying to create a new array for merged result
- Sorting arrays separately without merging
- Ignoring the no extra space constraint
arr1 and arr2 without extra space?Solution
Step 1: Check swapping syntax in Python
Python allows swapping two variables in one line using tuple unpacking:a, b = b, a.Step 2: Identify correct swap without extra variable
arr1[i], arr2[j] = arr2[j], arr1[i] uses this syntax correctly to swaparr1[i]andarr2[j]without extra space.Final Answer:
arr1[i], arr2[j] = arr2[j], arr1[i] -> Option DQuick Check:
Python swap syntax = arr1[i], arr2[j] = arr2[j], arr1[i] [OK]
- Assigning arr1[i] before arr2[j] loses original value
- Using temp variable unnecessarily
- Using arithmetic swap which can cause errors
arr1 and arr2 after running the following code?arr1 = [1, 5, 9, 10, 15, 20]
arr2 = [2, 3, 8, 13]
i = 5
j = 0
while i >= 0 and j < len(arr2):
if arr1[i] > arr2[j]:
arr1[i], arr2[j] = arr2[j], arr1[i]
i -= 1
j += 1
else:
i -= 1
arr1.sort()
arr2.sort()
print(arr1)
print(arr2)Solution
Step 1: Trace the while loop swaps
Start with i=5 (arr1[5]=20), j=0 (arr2[0]=2). Since 20 > 2, swap: arr1[5]=2, arr2[0]=20; i=4, j=1.
Next i=4 (15), j=1 (3): 15 > 3, swap: arr1[4]=3, arr2[1]=15; i=3, j=2.
i=3 (10), j=2 (8): 10 > 8, swap: arr1[3]=8, arr2[2]=10; i=2, j=3.
i=2 (9), j=3 (13): 9 > 13? No, so i=1.
i=1 (5), j=3 (13): 5 > 13? No, so i=0.
i=0 (1), j=3 (13): 1 > 13? No, so i=-1 loop ends.
After swaps: arr1 = [1, 5, 9, 8, 3, 2], arr2 = [20, 15, 10, 13].Step 2: Sort both arrays after swapping
The code sorts both arrays:
arr1.sort() -> [1, 2, 3, 5, 8, 9]
arr2.sort() -> [10, 13, 15, 20]Final Answer:
[1, 2, 3, 5, 8, 9] and [10, 13, 15, 20] -> Option BQuick Check:
Swapped and sorted arrays = [1,2,3,5,8,9], [10,13,15,20] [OK]
- Not decrementing i or incrementing j correctly
- Forgetting to sort arrays after swapping
- Confusing indices during swaps
arr1 and arr2 without extra space:def merge(arr1, arr2):
i = 0
j = 0
while i < len(arr1) and j < len(arr2):
if arr1[i] > arr2[j]:
arr1[i], arr2[j] = arr2[j], arr1[i]
i += 1
j += 1
arr1.sort()
arr2.sort()Solution
Step 1: Analyze loop increments
Both i and j are incremented every iteration regardless of swap condition, which can skip elements that need comparison.Step 2: Explain why skipping elements is wrong
To merge correctly, we must compare all relevant pairs. Incrementing both pointers blindly misses some comparisons, causing incorrect merge.Final Answer:
Incrementing both i and j in every iteration causes skipping elements -> Option CQuick Check:
Increment both pointers blindly = skip elements [OK]
- Incrementing both indices unconditionally
- Not sorting arrays after swaps
- Assuming while loop causes infinite loop here
arr1 = [1, 4, 7, 8, 10] and arr2 = [2, 3, 9], how can you merge them without extra space so that after merging, arr1 contains the first 5 smallest elements and arr2 contains the remaining elements, both sorted?Solution
Step 1: Understand the gap method
The gap method starts with a gap equal to the sum of lengths divided by 2, compares elements at gap distance across both arrays, and swaps if out of order. The gap reduces each iteration until it becomes zero.Step 2: Apply gap method to merge without extra space
This method efficiently merges two sorted arrays in place without extra memory, ensuring both arrays are sorted and merged correctly.Final Answer:
Use the gap method: compare elements at gap distance and swap if needed, reduce gap until 0 -> Option AQuick Check:
Gap method merges in place without extra space [OK]
- Trying to concatenate arrays which uses extra space
- Sorting arrays separately without merging
- Swapping without systematic gap reduction
Ready to prove it?
Pass the test and this pattern moves unknown
