Remove Duplicates from a Sorted Array
Problem
Read a sorted array. Remove the duplicates so that each value appears once. Print the remaining values in the same order.
Constraints
- 1 <= n <= 10^5, the array is sorted
Examples
Input
7 0 0 1 1 1 2 3
Output
0 1 2 3
Solutions
In a sorted array equal values stand together. We copy a value only when it differs from the last kept one.
/*
* Problem : Process an array.
* Input : n, then n integers.
* Output : The array without duplicates.
* Approach: Two pointers.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int[] solve(int[] a) {
// Step 1: unique is the number of different values found so far. The first element is always kept.
int unique = 1;
// Step 2: Compare every element with the last kept value.
for (int i = 1; i < a.length; i++) {
// Step 3: A new value goes to the next free place.
if (a[i] != a[unique - 1]) {
a[unique] = a[i];
unique++;
}
}
// Step 4: Return only the first "unique" elements.
return java.util.Arrays.copyOf(a, unique);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(Arrays.stream(solve(a)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
}
}
Hints (1)
- Where do equal values stand in a sorted array?