Count Occurrences in a Sorted Array

Pattern: Binary search on sorted arrays

medium

In a sorted array the copies of a value sit together. Their count is the upper bound minus the lower bound, two binary searches.

The problem

You are given a sorted array of whole numbers and a target. Return how many times the target appears, which is 0 if it does not appear. For example, [0, 0, 1, 1, 1, 2, 3] with target 1 gives 3, and [5, 5, 5, 5, 5, 5] with target 5 gives 6.

The function name countOccurrences matches the takeUforward practice page. Use the link above for the exact statement and limits.

Think first

  • Where do the copies of the target sit in a sorted array?
  • Which two boundaries mark the start and the end of that run?
  • Can one helper find both?

Hints

    Brute force, and why it fails

    Count with one pass: O(n). Finding one copy and walking both ways is O(n) when everything is the target. Two boundary searches are O(log n) always.

    The key insight

    A count in a sorted array is a distance between two boundaries. Boundaries are what binary search finds best.

    Dry run

    00 
    01 
    12 
    13 
    14 
    25 
    36 

    arr = [0, 0, 1, 1, 1, 2, 3] and target = 1. The 1s sit together at indexes 2 to 4.

    Step 1 of 4

    The plan

    function firstAbove(arr, x):
        lo = 0, hi = n
        while lo < hi:
            mid = lo + (hi - lo) / 2
            if arr[mid] > x: hi = mid
            else: lo = mid + 1
        return lo
    return firstAbove(arr, target) - firstAbove(arr, target - 1)
    

    Complexity

    Time
    O(log n)
    Space
    O(1)

    Two binary searches.

    Edge cases

    • Target missing, as in [1, 2, 4] with 3: both boundaries are 2, so 0.
    • Every value is the target: n.
    • Target above everything, as in [1, 3, 3] with 4: both boundaries are n, so 0.
    I've built my logic, show the code

    Java

    class Solution {
        public int countOccurrences(int[] arr, int target) {
            return firstAbove(arr, target) - firstAbove(arr, (long) target - 1);   // upper bound minus lower bound
        }
    
        private int firstAbove(int[] arr, long x) {        // first index with arr[i] > x
            int lo = 0, hi = arr.length;
            while (lo < hi) {
                int mid = lo + (hi - lo) / 2;
                if (arr[mid] > x) hi = mid;
                else lo = mid + 1;
            }
            return lo;
        }
    }

    C++

    class Solution {
    public:
        int countOccurrences(vector<int>& arr, int target) {
            return firstAbove(arr, target) - firstAbove(arr, static_cast<long long>(target) - 1);   // upper - lower
        }
    
        int firstAbove(vector<int>& arr, long long x) {    // first index with arr[i] > x
            int lo = 0, hi = static_cast<int>(arr.size());
            while (lo < hi) {
                int mid = lo + (hi - lo) / 2;
                if (arr[mid] > x) hi = mid;
                else lo = mid + 1;
            }
            return lo;
        }
    };

    Python

    class Solution:
        def countOccurrences(self, arr: list[int], target: int) -> int:
            return self.first_above(arr, target) - self.first_above(arr, target - 1)   # upper bound minus lower bound
    
        def first_above(self, arr: list[int], x: int) -> int:   # first index with arr[i] > x
            lo, hi = 0, len(arr)
            while lo < hi:
                mid = (lo + hi) // 2
                if arr[mid] > x:
                    hi = mid
                else:
                    lo = mid + 1
            return lo

    Common mistakes

    • Returning -1 when the target is missing. A count is 0.
    • Subtracting one too many, as in upper - lower - 1, which counts the gap between the indexes instead.
    • Walking from a found copy, which is O(n).

    Similar problems