Count Occurrences
Given an array of integers and a target value, count how many times the target appears in the array. Return the count as an integer.
For example, in the array [1, 2, 3, 2, 4, 2] with target 2, the count is 3 because 2 appears three times. If the target is not present, the count is 0. If the array is empty, the result is also 0.
This is a fundamental frequency-counting problem. Counting occurrences is a building block for more advanced statistics problems like mode, frequency analysis, and histogram generation. It teaches you linear search and iteration over array elements.
The simplest approach is to iterate through the array element by element and increment a counter whenever the current element matches the target. This requires no extra memory and runs in linear time. The array can contain negative numbers, zeros, and duplicates of other values — only the target value matters.
Edge cases include an empty array (return 0), an array where every element matches the target (the count equals the array length), and an array where no element matches (return 0). The solution should handle all these cases correctly.
Example Input & Output
All elements match
Single element match
Target not present
Count of 2 in [1,2,3,2,4,2]
All elements are 5
Algorithm Flow

Solution Approach
Iterate through the array and count matches using a simple loop and a counter variable.
Initialize count to 0. Loop over each element; if the element equals the target, increment count. After the loop, return count. For an empty array, the loop body never executes and count stays 0, which is correct.
Some languages offer built-in count methods. In Python, arr.count(target) does this in one call. In PHP, count(array_keys(arr, target)) works. In Rust, arr.iter().filter(|&n| *n == target).count() is idiomatic. These built-ins are typically implemented with the same linear iteration internally.
The time complexity is O(n) where n is the array length, since every element must be examined. The space complexity is O(1), using only a single integer counter.
Best Answers
class Solution {
public int solution(int[] nums, int target) {
int c=0;for(int n:nums){if(n==target)c++;}return c;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
