Bird
Raised Fist0
DSA Javaprogramming~20 mins

Merge Two Sorted Arrays Without Extra Space in DSA Java - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Master of In-Place Merge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of merging two sorted arrays without extra space
What is the output of the following Java code that merges two sorted arrays without using extra space?
DSA Java
public class MergeSortedArrays {
    public static void merge(int[] arr1, int[] arr2) {
        int n = arr1.length;
        int m = arr2.length;
        int i = 0, j = 0, k = n - 1;
        while (i <= k && j < m) {
            if (arr1[i] < arr2[j]) {
                i++;
            } else {
                int temp = arr2[j];
                arr2[j] = arr1[k];
                arr1[k] = temp;
                j++;
                k--;
            }
        }
        java.util.Arrays.sort(arr1);
        java.util.Arrays.sort(arr2);
    }

    public static void main(String[] args) {
        int[] arr1 = {1, 5, 9, 10, 15, 20};
        int[] arr2 = {2, 3, 8, 13};
        merge(arr1, arr2);
        System.out.print(java.util.Arrays.toString(arr1) + " ");
        System.out.print(java.util.Arrays.toString(arr2));
    }
}
A[1, 2, 3, 5, 8, 9] [10, 13, 15, 20]
B[1, 3, 5, 8, 9, 10] [2, 13, 15, 20]
C[1, 2, 3, 5, 8, 9] [10, 15, 20, 13]
D[1, 2, 3, 5, 9, 10] [8, 13, 15, 20]
Attempts:
2 left
💡 Hint
Focus on how elements are swapped between the end of the first array and the start of the second array, then both arrays are sorted.
🧠 Conceptual
intermediate
1:30remaining
Understanding the key idea behind merging without extra space
What is the main idea behind merging two sorted arrays without using extra space?
AUse a linked list to merge elements in sorted order.
BCopy all elements into a new array and sort it.
CSwap elements between arrays to ensure smaller elements are in the first array, then sort both arrays.
DSort both arrays independently without swapping elements.
Attempts:
2 left
💡 Hint
Think about how to avoid extra memory by rearranging elements inside the given arrays.
🔧 Debug
advanced
2:00remaining
Identify the error in this merge implementation
What error will occur if we replace the line 'while (i <= k && j < m)' with 'while (i < k && j <= m)' in the merge method?
DSA Java
public static void merge(int[] arr1, int[] arr2) {
    int n = arr1.length;
    int m = arr2.length;
    int i = 0, j = 0, k = n - 1;
    while (i < k && j <= m) {
        if (arr1[i] < arr2[j]) {
            i++;
        } else {
            int temp = arr2[j];
            arr2[j] = arr1[k];
            arr1[k] = temp;
            j++;
            k--;
        }
    }
    java.util.Arrays.sort(arr1);
    java.util.Arrays.sort(arr2);
}
ANullPointerException
BNo error, code runs correctly
CInfinite loop
DArrayIndexOutOfBoundsException
Attempts:
2 left
💡 Hint
Check the loop condition and array index usage carefully.
❓ Predict Output
advanced
2:00remaining
Result after merging arrays with duplicates
What is the output of the following code after merging two sorted arrays with duplicate elements without extra space?
DSA Java
public class MergeSortedArrays {
    public static void merge(int[] arr1, int[] arr2) {
        int n = arr1.length;
        int m = arr2.length;
        int i = 0, j = 0, k = n - 1;
        while (i <= k && j < m) {
            if (arr1[i] < arr2[j]) {
                i++;
            } else {
                int temp = arr2[j];
                arr2[j] = arr1[k];
                arr1[k] = temp;
                j++;
                k--;
            }
        }
        java.util.Arrays.sort(arr1);
        java.util.Arrays.sort(arr2);
    }

    public static void main(String[] args) {
        int[] arr1 = {1, 3, 5, 7, 9};
        int[] arr2 = {3, 5, 7, 11, 13};
        merge(arr1, arr2);
        System.out.print(java.util.Arrays.toString(arr1) + " ");
        System.out.print(java.util.Arrays.toString(arr2));
    }
}
A[1, 3, 5, 7, 7] [3, 5, 9, 11, 13]
B[1, 3, 3, 5, 5] [7, 7, 9, 11, 13]
C[1, 3, 3, 5, 7] [5, 7, 9, 11, 13]
D[1, 3, 5, 7, 9] [3, 5, 7, 11, 13]
Attempts:
2 left
💡 Hint
Duplicates are swapped and sorted just like other elements.
🧠 Conceptual
expert
2:30remaining
Why is sorting both arrays after swapping necessary?
In the merge without extra space approach, why do we sort both arrays after swapping elements?
ABecause swapping only ensures elements are roughly partitioned, sorting finalizes the order within each array.
BBecause sorting is required to remove duplicates after swapping.
CBecause sorting is needed to merge arrays into a single array.
DBecause swapping sorts the arrays automatically, so sorting is redundant.
Attempts:
2 left
💡 Hint
Think about what swapping achieves and what sorting completes.

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