Given a sorted array of integers nums, count the number of occurrences of a given value.
Example:
Input: nums = [1, 2, 2, 2, 4, 5], value = 2
Output: 3
Explanation: the value 2 appears 3 times in the array
Your algorithm should run in O(log n) time and use O(1) extra space.
/**
 * Function to find the first occurrence of a value in a sorted array
 * @param {number[]} nums - Sorted array of integers
 * @param {number} value - Value to find
 * @return {number} - Index of the first occurrence
 */
function findFirstOccurrence(nums, value) {
    let left = 0;
    let right = nums.length - 1;
    let result = -1;
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (nums[mid] >= value) {
            if (nums[mid] === value) {
                result = mid;
            }
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return result;
}
/**
 * Function to find the last occurrence of a value in a sorted array
 * @param {number[]} nums - Sorted array of integers
 * @param {number} value - Value to find
 * @return {number} - Index of the last occurrence
 */
function findLastOccurrence(nums, value) {
    let left = 0;
    let right = nums.length - 1;
    let result = -1;
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (nums[mid] <= value) {
            if (nums[mid] === value) {
                result = mid;
            }
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return result;
}
/**
 * Function to count the number of occurrences of a value in a sorted array
 * @param {number[]} nums - Sorted array of integers
 * @param {number} value - Value to count
 * @return {number} - Number of occurrences
 */
function countOccurrences(nums, value) {
    const first = findFirstOccurrence(nums, value);
    if (first === -1) return 0;
    const last = findLastOccurrence(nums, value);
    return last - first + 1;
}
// Example usage
const nums = [1, 2, 2, 2, 4, 5];
const value = 2;
console.log(countOccurrences(nums, value)); // Output: 3
Our interactive tutorials and AI-assisted learning will help you master problem-solving skills and teach you the algorithms to know for coding interviews.
Start Coding for FREE