how to remove duplicates in a sorted array code example
Example 1: remove duplicates from array
let chars = ['A', 'B', 'A', 'C', 'B'];
let uniqueChars = [...new Set(chars)];
console.log(uniqueChars);
output:
[ 'A', 'B', 'C' ]
Example 2: remove duplicates from sorted array
// Java
public int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[j] != nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
Example 3: remove duplicates in sorted array python
def removeDuplicate(arr, n):
j = 0
for i in range(0, n-1):
if (arr[i] != arr[i+1]):
arr[j] = arr[i]
j = j+1
arr[j] = arr[n-1]
j = j+1
for i in range(0, j):
print("%d"%(arr[i]), end = " ")
arr = [1, 3, 5, 5, 7, 9]
n = len(arr)
if (n > 1):
removeDuplicate(arr, n)