Remove Duplicates from Sorted Array
Problem Statement
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of nums.
Do not allocate extra space for another array. You must do this by modifying the input array in-place with minimal extra memory usage.
Method Signature
public static int removeDuplicates(int[] nums)
Examples
Example 1:
Input: nums = [1,1,2]
Output: 2
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
Result array: [1,2,_]
Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5
Explanation: Your function should return k = 5, with the first five elements being 0,1,2,3,4.
Result array: [0,1,2,3,4,_,_,_,_,_]
Test Your Solution
import java.util.Arrays;
public class RemoveDuplicatesTest {
public static void main(String[] args) {
// Test case 1
int[] test1 = {1, 1, 2};
int k1 = removeDuplicates(test1);
System.out.println("Test 1 - Length: " + k1); // Expected: 2
System.out.println("Array: " + Arrays.toString(Arrays.copyOf(test1, k1))); // [1, 2]
// Test case 2
int[] test2 = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4};
int k2 = removeDuplicates(test2);
System.out.println("Test 2 - Length: " + k2); // Expected: 5
System.out.println("Array: " + Arrays.toString(Arrays.copyOf(test2, k2))); // [0, 1, 2, 3, 4]
// Test case 3 - no duplicates
int[] test3 = {1, 2, 3, 4, 5};
int k3 = removeDuplicates(test3);
System.out.println("Test 3 - Length: " + k3); // Expected: 5
System.out.println("Array: " + Arrays.toString(Arrays.copyOf(test3, k3))); // [1, 2, 3, 4, 5]
// Test case 4 - all same
int[] test4 = {1, 1, 1, 1};
int k4 = removeDuplicates(test4);
System.out.println("Test 4 - Length: " + k4); // Expected: 1
System.out.println("Array: " + Arrays.toString(Arrays.copyOf(test4, k4))); // [1]
}
// Your implementation goes here
public static int removeDuplicates(int[] nums) {
// TODO: Implement remove duplicates
return 0;
}
}
Extension Challenges
- Remove Duplicates Variation: Allow each element to appear at most twice
- Remove Specific Element: Remove all instances of a given value
- Count Unique Elements: Return count without modifying array
- Preserve Original: Remove duplicates while keeping original array unchanged