Skip to content

Instantly share code, notes, and snippets.

@KeshariPiyush24
Created September 21, 2024 09:36
Show Gist options
  • Save KeshariPiyush24/7e0ef1dac53f43f840d186d0faf4a3b4 to your computer and use it in GitHub Desktop.
Save KeshariPiyush24/7e0ef1dac53f43f840d186d0faf4a3b4 to your computer and use it in GitHub Desktop.
Frequency In A Sorted Array

Question: Frequency In A Sorted Array

Intution:

Time Complexity: $$O(log(n))$$

Space Complexity: $$O(1)$$

Solution:

public class Solution {
	public static int countOccurrences(int[] arr, int x) {
		int n = arr.length;
		return upperBound(arr, x, n) - lowerBound(arr, x, n);
	}

	public static int lowerBound(int[] arr, int x, int n) {
        int low = 0;
        int high = n - 1;
        int ans = n;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] < x) low = mid + 1;
            else {
                ans = mid;
                high = mid - 1;
            }
        }
        return ans;
    }
	
	public static int upperBound(int[] arr, int x, int n){
        int low = 0;
        int high = n - 1;
        int ans = n;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] <= x) low = mid + 1;
            else {
                ans = mid;
                high = mid - 1;
            }
        }
        return ans;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment