Count occurrence GFG

 package com.company;


public class countOccurrence {
// Number of times an element occur in an array
// 1. Naive solution
public static int getOccurrence(int[] arr, int x) {
int n = arr.length;
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
count++;
}
}
return count;
}

// 2. Efficient solution
public static int firstIndex(int[] arr, int x) {
int n = arr.length;
// Finding the index of first occurrence of an element
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == x) {
if (mid == 0 || arr[mid] != arr[mid - 1]) {
return mid;
} else
high = mid - 1;
} else if (arr[mid] > x) {
high = mid - 1;
} else
low = mid + 1;
}
return -1;
}
public static int lastIndex(int[] arr, int x) {
int n = arr.length;
int low = 0; int high = n - 1;
while(low <= high) {
int mid = (low + high) / 2;
if(arr[mid] == x) {
if(mid == n - 1 || arr[mid + 1 ] != x) {
return mid;
}
else
low = mid + 1;
}

else if(arr[mid] > x) {
high =mid - 1;
}
else
low = mid + 1;
}
return -1;
}

// Calling the method
public static int get(int[] arr, int x) {
int n = arr.length;
int count = 0;
int a = getCount(arr, x);
if (a == -1) {
return 0;
}
for (int i = a; i < n - 1; i++) {
if (arr[i] == arr[a]) {
count++;
}
}
return count;
}
//Best solution using first occurrence and last occurrence of an element
public static int getCount(int[] arr, int x) {
int n = arr.length;
int f = firstIndex(arr, x);
if(f == -1){
return 0;
}

return (lastIndex(arr, x) - f + 1);
}
public static void main(String[] args) {
int[] array = {2, 5, 6, 6, 6, 7, 8};
System.out.println(getCount(array, 68));

}

}

Comments