Bird
Raised Fist0
DSA Pythonprogramming

Merge Two Sorted Arrays Without Extra Space in DSA Python

Choose your learning style10 modes available
Mental Model
We want to combine two sorted lists into one sorted order without using extra space. We do this by swapping elements between the two lists to keep them sorted.
Analogy: Imagine you have two sorted stacks of books on two tables. Instead of moving books to a new table, you swap books between the tables to keep both stacks sorted.
Array1: [1, 5, 9, 10, 15, 20]
Array2: [2, 3, 8, 13]
Dry Run Walkthrough
Input: array1: [1, 5, 9, 10, 15, 20], array2: [2, 3, 8, 13]
Goal: Merge both arrays so that after merging, array1 and array2 together represent the sorted order without using extra space.
Step 1: Compare arr1[5]=20 > arr2[0]=2, swap them
array1: [1, 5, 9, 10, 15, 2]
array2: [20, 3, 8, 13]
Why: Swap 20 and 2 because 20 > 2 to keep smaller elements in array1
Step 2: Compare arr1[4]=15 > arr2[1]=3, swap them
array1: [1, 5, 9, 10, 3, 2]
array2: [20, 15, 8, 13]
Why: Keep smaller elements in array1 and larger in array2
Step 3: Compare arr1[3]=10 > arr2[2]=8, swap them
array1: [1, 5, 9, 8, 3, 2]
array2: [20, 15, 10, 13]
Why: Continue swapping to maintain order
Step 4: Compare arr1[2]=9 <= arr2[3]=13, no more swaps needed, break
array1: [1, 5, 9, 8, 3, 2]
array2: [20, 15, 10, 13]
Why: arr1[i] <= arr2[j], so remaining elements are in correct relative order
Step 5: Sort both arrays individually after swaps
array1: [1, 2, 3, 5, 8, 9]
array2: [10, 13, 15, 20]
Why: Sorting arrays after swaps ensures final sorted order without extra space
Result:
array1: [1, 2, 3, 5, 8, 9]
array2: [10, 13, 15, 20]
Annotated Code
DSA Python
def merge_without_extra_space(arr1, arr2):
    n, m = len(arr1), len(arr2)
    i, j = n - 1, 0
    while i >= 0 and j < m:
        if arr1[i] > arr2[j]:
            arr1[i], arr2[j] = arr2[j], arr1[i]  # swap bigger in arr1 with smaller in arr2
            i -= 1
            j += 1
        else:
            break  # no more swaps needed if arr1[i] <= arr2[j]
    arr1.sort()  # sort arr1 after swaps
    arr2.sort()  # sort arr2 after swaps


# Driver code
arr1 = [1, 5, 9, 10, 15, 20]
arr2 = [2, 3, 8, 13]
merge_without_extra_space(arr1, arr2)
print('array1:', arr1)
print('array2:', arr2)
while i >= 0 and j < m:
loop to compare elements from end of arr1 and start of arr2
if arr1[i] > arr2[j]:
check if swap is needed to keep smaller elements in arr1
arr1[i], arr2[j] = arr2[j], arr1[i]
swap elements between arrays
i -= 1 j += 1
move pointers inward after swap
else: break
stop if no more swaps needed
arr1.sort() arr2.sort()
sort arrays individually after swaps to finalize order
OutputSuccess
array1: [1, 2, 3, 5, 8, 9] array2: [10, 13, 15, 20]
Complexity Analysis
Time: O(n log n + m log m) because sorting both arrays after swapping takes most time
Space: O(1) because no extra space is used except variables for indices
vs Alternative: Naive approach uses extra space to merge arrays, which costs O(n + m) space; this method saves space but requires sorting after swaps.
Edge Cases
One or both arrays empty
Function handles gracefully; sorting empty arrays is safe and no swaps occur
DSA Python
while i >= 0 and j < m:
Arrays already fully sorted with no overlapping elements
No swaps happen; function exits early at break
DSA Python
else:
    break
Arrays with duplicate elements
Duplicates are handled correctly by swaps and sorting
DSA Python
arr1.sort()
arr2.sort()
When to Use This Pattern
When asked to merge two sorted arrays without extra space, use the swapping and sorting pattern to rearrange elements in place efficiently.
Common Mistakes
Mistake: Trying to merge by shifting elements one by one causing O(n*m) time
Fix: Use two pointers from opposite ends and swap, then sort arrays once
Mistake: Not sorting arrays after swaps, resulting in unsorted arrays
Fix: Always sort both arrays after swapping to finalize order
Summary
Merges two sorted arrays into sorted order without extra space by swapping and sorting.
Use when you must merge sorted arrays but cannot use extra memory.
The key is swapping elements from the end of first and start of second array, then sorting both.

Practice

(1/5)
1. What is the main goal when merging two sorted arrays without extra space?
easy
A. Combine both arrays into one sorted array without using extra memory
B. Sort each array separately using extra space
C. Copy elements from one array to another without sorting
D. Create a new array to hold merged elements

Solution

  1. 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.
  2. Step 2: Identify the correct approach

    We must rearrange elements within the given arrays to maintain sorted order without additional memory.
  3. Final Answer:

    Combine both arrays into one sorted array without using extra memory -> Option A
  4. Quick Check:

    Merge without extra space = Combine in-place [OK]
Hint: Merge by swapping elements in place without extra arrays [OK]
Common Mistakes:
  • Trying to create a new array for merged result
  • Sorting arrays separately without merging
  • Ignoring the no extra space constraint
2. Which of the following Python code snippets correctly swaps elements between two arrays arr1 and arr2 without extra space?
easy
A. arr1[i] = arr1[i] + arr2[j]; arr1[i] = arr1[i] - arr2[j]; arr2[j] = arr1[i]
B. arr1[i] = arr2[j]; arr2[j] = arr1[i]
C. temp = arr1[i]; arr1[i] = arr2[j]; arr2[j] = temp
D. arr1[i], arr2[j] = arr2[j], arr1[i]

Solution

  1. Step 1: Check swapping syntax in Python

    Python allows swapping two variables in one line using tuple unpacking: a, b = b, a.
  2. Step 2: Identify correct swap without extra variable

    arr1[i], arr2[j] = arr2[j], arr1[i] uses this syntax correctly to swap arr1[i] and arr2[j] without extra space.
  3. Final Answer:

    arr1[i], arr2[j] = arr2[j], arr1[i] -> Option D
  4. Quick Check:

    Python swap syntax = arr1[i], arr2[j] = arr2[j], arr1[i] [OK]
Hint: Use Python tuple unpacking for swap: a, b = b, a [OK]
Common Mistakes:
  • Assigning arr1[i] before arr2[j] loses original value
  • Using temp variable unnecessarily
  • Using arithmetic swap which can cause errors
3. What will be the content of 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)
medium
A. [1, 5, 8, 10, 13, 15] and [2, 3, 9, 20]
B. [1, 2, 3, 5, 8, 9] and [10, 13, 15, 20]
C. [1, 5, 9, 8, 3, 2] and [20, 15, 10, 13]
D. [1, 3, 5, 8, 9, 10] and [2, 13, 15, 20]

Solution

  1. 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].
  2. 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]
  3. Final Answer:

    [1, 2, 3, 5, 8, 9] and [10, 13, 15, 20] -> Option B
  4. Quick Check:

    Swapped and sorted arrays = [1,2,3,5,8,9], [10,13,15,20] [OK]
Hint: Swap bigger in arr1 with smaller in arr2, then sort both [OK]
Common Mistakes:
  • Not decrementing i or incrementing j correctly
  • Forgetting to sort arrays after swapping
  • Confusing indices during swaps
4. Identify the error in the following code snippet intended to merge two sorted arrays 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()
medium
A. Sorting arrays after swapping is unnecessary
B. Swapping elements without checking if arr1[i] is smaller
C. Incrementing both i and j in every iteration causes skipping elements
D. Using while loop instead of for loop causes infinite loop

Solution

  1. Step 1: Analyze loop increments

    Both i and j are incremented every iteration regardless of swap condition, which can skip elements that need comparison.
  2. 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.
  3. Final Answer:

    Incrementing both i and j in every iteration causes skipping elements -> Option C
  4. Quick Check:

    Increment both pointers blindly = skip elements [OK]
Hint: Increment pointers only when appropriate to avoid skipping [OK]
Common Mistakes:
  • Incrementing both indices unconditionally
  • Not sorting arrays after swaps
  • Assuming while loop causes infinite loop here
5. Given two sorted arrays 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?
hard
A. Use the gap method: compare elements at gap distance and swap if needed, reduce gap until 0
B. Concatenate both arrays and sort the combined array
C. Swap elements only if arr1[i] is greater than arr2[j], then sort both arrays
D. Copy arr2 elements into arr1 and sort arr1

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Use the gap method: compare elements at gap distance and swap if needed, reduce gap until 0 -> Option A
  4. Quick Check:

    Gap method merges in place without extra space [OK]
Hint: Use gap method to merge by reducing gap and swapping [OK]
Common Mistakes:
  • Trying to concatenate arrays which uses extra space
  • Sorting arrays separately without merging
  • Swapping without systematic gap reduction
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard