How to merge two sorted arrays into a single sorted array in Java without using extra space?
I recently switched to After trying multiple solutions online, I still can't figure this out... I'm trying to merge two pre-sorted integer arrays in Java into a single sorted array without using any additional space. The arrays are of fixed size; for instance, `arr1` has 5 elements and `arr2` has 3. My goal is to do this in-place by modifying one of the original arrays. I attempted to use a two-pointer approach, but I'm running into issues with handling the elements correctly, especially at the end of the arrays. Hereβs what I have so far: ```java public class MergeSortedArrays { public static void merge(int[] arr1, int[] arr2, int m, int n) { int i = m - 1; // Last index of arr1 int j = n - 1; // Last index of arr2 int k = m + n - 1; // Last index of merged array // Merge arr2 into arr1 from the end while (i >= 0 && j >= 0) { if (arr1[i] > arr2[j]) { arr1[k--] = arr1[i--]; } else { arr1[k--] = arr2[j--]; } } // Copy remaining elements of arr2, if any while (j >= 0) { arr1[k--] = arr2[j--]; } } } ``` When I run this code, I get `ArrayIndexOutOfBoundsException` if `arr1` has no remaining space left for insertion. I am using Java 11. I realize that I need to ensure that both arrays are dynamically handled since I'm not allocating new space. Any ideas on how to adjust my approach to prevent this behavior? Also, are there better practices for merging without additional space that I might have missed? I'd be grateful for any help.