Intermediate Level

Implement the countTargetInSortedArray method that counts how many times the target appears in a sorted array.

The input contains a sorted integer array nums, its length size, and an integer target. Your task is to count how many times target appears in the array.

For example, in [1,2,2,2,3], the value 2 appears three times, so the answer is 3. If the target is not found, return 0.

Example 1

Input
nums (int[]) = [1,2,2,2,3]
size (int) = 5
target (int) = 2
Returns (int) 3

Example 2

Input
nums (int[]) = [1,3,5]
size (int) = 3
target (int) = 2
Returns (int) 0

Example 3

Input
nums (int[]) = [4,4,4,4]
size (int) = 4
target (int) = 4
Returns (int) 4

Because the array is sorted, all occurrences of the target will be together.

A simple solution is to scan the array and count every value equal to target. You may stop early after passing the target in a sorted array, but counting matches directly is enough for these inputs.

Pseudocode:

function countTargetInSortedArray(nums, size, target):
    count = 0
    for i from 0 to size - 1:
        if nums[i] == target:
            count++
    return count
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.