Bird
Raised Fist0
DSA Javaprogramming~5 mins

Merge Two Sorted Arrays Without Extra Space in DSA Java - Time & Space Complexity

Choose your learning style10 modes available
Time Complexity: Merge Two Sorted Arrays Without Extra Space
O(n * m)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
10Up to 10 * 10 = 100
100Up to 100 * 100 = 10,000
1000Up 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.

Final Time Complexity

Time Complexity: O(n * m)

This means the time taken grows proportionally to the product of the sizes of the two arrays.

Common Mistake

[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.

Interview Connect

Understanding this time complexity helps you explain trade-offs when merging arrays without extra space, a common real-world problem where memory is limited.

Self-Check

"What if we used a gap method to reduce the number of shifts? How would the time complexity change?"

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 sequence without using extra memory
B. Copy all elements into a new array and sort it
C. Sort each array separately without merging
D. Use a temporary array to hold merged elements

Solution

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

    Using in-place techniques like swapping elements between arrays and sorting them ensures no extra space is used.
  3. Final Answer:

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

    Merge without extra space = Combine in-place [OK]
Hint: Remember: no extra array means in-place merging [OK]
Common Mistakes:
  • Thinking extra array is allowed
  • Sorting arrays separately without merging
  • Using extra memory for temporary storage
2. Which of the following Java code snippets correctly swaps elements between two arrays arr1 and arr2 at indices i and j without extra space?
easy
A. arr1[i] = arr1[j]; arr2[j] = arr2[i];
B. arr1[i] = arr2[j]; arr2[j] = arr1[i];
C. int temp = arr2[j]; arr1[i] = arr2[j]; arr2[j] = temp;
D. int temp = arr1[i]; arr1[i] = arr2[j]; arr2[j] = temp;

Solution

  1. Step 1: Check the swap logic

    Swapping requires a temporary variable to hold one value while assigning the other to avoid overwriting.
  2. 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.
  3. Final Answer:

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

    Swap needs temp variable = int temp = arr1[i]; arr1[i] = arr2[j]; arr2[j] = temp; [OK]
Hint: Always use a temp variable to swap two values safely [OK]
Common Mistakes:
  • Assigning without temp causes overwriting
  • Swapping elements within the same array incorrectly
  • Confusing indices during swap
3. Given two sorted arrays 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?
medium
A. arr1 = [1, 2, 3, 8], arr2 = [5, 9, 10, 13]
B. arr1 = [1, 2, 3, 5], arr2 = [8, 9, 10, 13]
C. arr1 = [1, 3, 5, 8], arr2 = [2, 9, 10, 13]
D. arr1 = [1, 2, 5, 8], arr2 = [3, 9, 10, 13]

Solution

  1. 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.
  2. Step 2: Final sorted arrays after merging

    After swapping and sorting, arr1 becomes [1, 2, 3, 5] and arr2 becomes [8, 9, 10, 13].
  3. Final Answer:

    arr1 = [1, 2, 3, 5], arr2 = [8, 9, 10, 13] -> Option B
  4. Quick Check:

    In-place merge sorts arrays = arr1 = [1, 2, 3, 5], arr2 = [8, 9, 10, 13] [OK]
Hint: Swap bigger arr1 elements with smaller arr2, then sort both [OK]
Common Mistakes:
  • Not sorting arrays after swapping
  • Swapping incorrectly leading to unsorted arrays
  • Mixing indices during swaps
4. Identify the error in the following code snippet for merging two sorted arrays without extra space:
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);
  }
}
medium
A. Using Arrays.sort on arr1 instead of arr2 is required
B. Swapping elements without checking arr2 length causes error
C. Sorting arr2 inside the loop causes unnecessary repeated sorting
D. Loop should run until arr2.length instead of arr1.length

Solution

  1. 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.
  2. Step 2: Suggest optimization

    Sorting arr2 once after all swaps or using a better approach like gap method improves performance.
  3. Final Answer:

    Sorting arr2 inside the loop causes unnecessary repeated sorting -> Option C
  4. Quick Check:

    Repeated sorting inside loop = inefficiency [OK]
Hint: Avoid sorting inside loops; sort once after swaps [OK]
Common Mistakes:
  • Sorting arr2 repeatedly inside loop
  • Confusing loop limits between arrays
  • Ignoring performance impact of repeated sorting
5. You have two sorted arrays 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?
hard
A. arr1 = [1, 2, 3, 4, 7], arr2 = [8, 9, 10]
B. arr1 = [1, 2, 3, 4, 9], arr2 = [7, 8, 10]
C. arr1 = [1, 3, 4, 7, 8], arr2 = [2, 9, 10]
D. arr1 = [1, 2, 4, 7, 8], arr2 = [3, 9, 10]

Solution

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

    arr1 = [1, 2, 3, 4, 7], arr2 = [8, 9, 10] -> Option A
  4. Quick Check:

    Gap method sorts arrays in-place = arr1 = [1, 2, 3, 4, 7], arr2 = [8, 9, 10] [OK]
Hint: Use gap method: reduce gap, swap if needed, repeat until gap=0 [OK]
Common Mistakes:
  • Not reducing gap correctly
  • Swapping wrong elements across arrays
  • Confusing gap calculation with array lengths
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