Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Binary Search

Count Occurrences in a Sorted Array

Easy · Binary Search · Asked at Amazon, Microsoft, TCS, Infosys, Wipro

The array is sorted in non-decreasing order. For each query x, print how many times x occurs in the array.

Input

First line: n. Second line: n space-separated integers. Third line: q. Fourth line: the q queries.

Output

q lines — the count for each query.

Constraints

count(x) = (first index with value > x) − (first index with value ≥ x). Both are binary searches (upper bound and lower bound), so each query is O(log n).

Example 1

Input

7
1 1 2 2 2 2 3
3
2 4 1

Output

4
0
2

Hints

  1. All copies of x sit next to each other in a sorted array.
  2. The first index with a value ≥ x and the first with a value > x bound that block.
  3. Both are binary searches.

Approach

For each query compute lower_bound(x) (first index with a[i] ≥ x) and upper_bound(x) (first index with a[i] > x); their difference is the count, and 0 when x is absent. Each query costs two O(log n) searches.

Complexity: O((n + q) log n) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<long long> a(n);
    for (auto &x : a) cin >> x;
    int q;
    cin >> q;
    while (q--) {
        long long x;
        cin >> x;
        cout << upper_bound(a.begin(), a.end(), x) - lower_bound(a.begin(), a.end(), x) << "\n";
    }
    return 0;
}

Python solution

import sys
from bisect import bisect_left, bisect_right

data = list(map(int, sys.stdin.read().split()))
n = data[0]
a = data[1 : 1 + n]
q = data[1 + n]
out = [bisect_right(a, x) - bisect_left(a, x) for x in data[2 + n : 2 + n + q]]
print("\n".join(map(str, out)))

Java solution

import java.io.*;

public class Main {
    static long[] a;

    static int bound(long x, boolean strict) {
        int lo = 0, hi = a.length;
        while (lo < hi) {
            int m = (lo + hi) >>> 1;
            if (strict ? a[m] <= x : a[m] < x) lo = m + 1;
            else hi = m;
        }
        return lo;
    }

    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        a = new long[n];
        for (int i = 0; i < n; i++) {
            in.nextToken();
            a[i] = (long) in.nval;
        }
        in.nextToken();
        int q = (int) in.nval;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < q; i++) {
            in.nextToken();
            long x = (long) in.nval;
            sb.append(bound(x, true) - bound(x, false)).append('\n');
        }
        System.out.print(sb);
    }
}

Solve Count Occurrences in a Sorted Array online · All practice problems