Find duplicates and count in sorted array
// Time complexity : O(n)
class PrintDuplicateAndCounts {
static void printDuplicates(int[] array) {
for(int i = 0; i < array.length - 1; i++) {
if(array[i] == array[i+1]) {
// duplicate found
int j = i + 1;
while(array[i] == array[j]) {
// continue iterating array to count all duplicates of this perticular element
j++;
}
System.out.println(array[i] + " appeared " + (j-i) + " times");
i = j - 1;
}
}
}
static void printDuplicates_dp(int[] array) {
int smallest = array[0];
int largest = array[array.length-1];
int[] dp = new int[largest - smallest + 1];
for(int i = 0; i < array.length; i++) {
dp[array[i]-smallest]++;
}
int lastDuplicate = -1;
for(int i = 0; i < array.length; i++) {
if(dp[array[i]-smallest] > 1 && array[i] != lastDuplicate) {
System.out.println(array[i] + " appeared " + dp[array[i]-smallest] + " times");
lastDuplicate = array[i];
}
}
}
public static void main (String[] args) {
int[] array = new int[] {3, 6, 8, 8, 10, 12, 15, 15, 15, 20};
printDuplicates(array);
printDuplicates_dp(array);
}
}
Comments
Post a Comment