Code Logo

Count Occurrences

Published at25 Jul 2026
Statistics Easy 0 views
Like0

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

Example 1
Input
[7,7,7,7,7],7
Output
5
Explanation

All elements match

Example 2
Input
[10],10
Output
1
Explanation

Single element match

Example 3
Input
[1,2,3],4
Output
0
Explanation

Target not present

Example 4
Input
[1,2,3,2,4,2],2
Output
3
Explanation

Count of 2 in [1,2,3,2,4,2]

Example 5
Input
[5,5,5,5],5
Output
4
Explanation

All elements are 5

Algorithm Flow

Recommendation Algorithm Flow for Count Occurrences
Recommendation Algorithm Flow for Count Occurrences

Solution Approach

Iterate through the array and count matches using a simple loop and a counter variable.

function solution(arr, target) {
  var count = 0;
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === target) count++;
  }
  return count;
}

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

java
class Solution {
    public int solution(int[] nums, int target) {
        int c=0;for(int n:nums){if(n==target)c++;}return c;
    }
}