CodexBloom - Programming Q&A Platform

Java - Difficulty Merging Two Sorted Arrays While Maintaining Order and Avoiding Duplicates

๐Ÿ‘€ Views: 15 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-16
arrays sorting duplicates algorithms Java

I'm trying to merge two sorted arrays in Java while ensuring that the resulting array maintains order and does not contain duplicates. Iโ€™m using Java 11 and I started by creating a method that utilizes the two-pointer technique. However, I'm working with issues with duplicates being included in the final array, and Iโ€™m not sure where Iโ€™m going wrong. Hereโ€™s my code snippet: ```java public int[] mergeSortedArrays(int[] arr1, int[] arr2) { int n = arr1.length; int m = arr2.length; int[] merged = new int[n + m]; int i = 0, j = 0, k = 0; while (i < n && j < m) { if (arr1[i] < arr2[j]) { merged[k++] = arr1[i++]; } else if (arr1[i] > arr2[j]) { merged[k++] = arr2[j++]; } else { // Handles duplicates merged[k++] = arr1[i++]; j++; } } while (i < n) { merged[k++] = arr1[i++]; } while (j < m) { merged[k++] = arr2[j++]; } return Arrays.copyOf(merged, k); // Resize to k } ``` I thought the logic was correct, especially the part where I handle potential duplicates. But when I run the method with the following arrays: ```java int[] arr1 = {1, 2, 3, 4, 4}; int[] arr2 = {2, 3, 5, 6}; ``` I get `[1, 2, 2, 3, 3, 4, 4, 5, 6]` as output instead of `[1, 2, 3, 4, 5, 6]`. I suspect the question lies in how Iโ€™m merging the arrays and handling duplicates. I've also tried using a HashSet to filter duplicates after the merge, but that feels inefficient and not in line with the goal of merging sorted arrays directly. Any suggestions on how to fix this? Am I missing a crucial step in my logic? I'd really appreciate any guidance on this.