Count Occurrences in a Sorted Array

medium Searching and Sorting

Problem

The array is sorted from small to big and may have duplicates. Print how many times the number k appears. Use two binary searches (first place and first place after k): O(log n).

Constraints

  • 1 <= n <= 10^5

Examples

Input

5
1 2 2 2 3
2

Output

3

Solutions

Best approachTime O(log n)Space O(1)

Equal numbers sit together in a sorted array. Two binary searches find where the group starts and where it ends. The count is the difference. O(log n).

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Count a number.
 * Input   : n, the array, then k.
 * Output  : The count.
 * Approach: Two lower bounds.
 * Time    : O(log n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
        // Index of the first number that is not smaller than target (the lower bound).
        private static int lowerBound(int[] a, int target) {
            int low = 0;
            int high = a.length;
            while (low < high) {
                int middle = low + (high - low) / 2;
                if (a[middle] < target) {
                    low = middle + 1;
                } else {
                    high = middle;
                }
            }
            return low;
        }

    // This method solves the task. It receives the input and returns the answer.
    static int solve(int[] a, int k) {
        // Step 1: The first place of k is the lower bound of k. The first place after all k is the lower bound of k + 1.
        // Step 2: The count is the distance between the two places.
        return lowerBound(a, k + 1) - lowerBound(a, k);
    }

    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();
        }
        int k = scanner.nextInt();
        System.out.println(solve(a, k));
    }
}
Hints (2)
  1. Why is the lower bound of k + 1 the end of the group?
  2. What is the answer if k is missing?