Count Occurrences of a Value

Solve this Problem
Easy5 min
Topics
Companies
Given an array nums and a target, return how many times the target appears. Counting combines a linear scan with a counter. Unlike searching, it can never stop early: every element might be another match, so an unsorted array always needs one full pass. (If the array were sorted, all copies would sit together and binary searchBinary SearchRepeatedly halving a sorted range to find a value in O(log n) steps. could find their range much faster.)

Test Case 1:

Input:nums = [3, 7, 3, 1, 3], target = 3
Output:3
Explanation:3 appears at indexes 0, 2 and 4.

Test Case 2:

Input:nums = [3, 7], target = 5
Output:0
Explanation:Absent values occur zero times.

Constraints

  • ◆1 ≤ nums.length ≤ 1000
  • ◆-1000000 ≤ nums[i], target ≤ 1000000

Try the Dry Run

Approach & Solutions

Count in a LoopOptimal

Walk the whole array and add one to a counter every time an element equals the target. Unlike a search, counting can never stop early — any element could be another match.

TimeO(n)
SpaceO(1)
class Solution { public int countOccurrences(int[] nums, int target) { int count = 0; for (int value : nums) { if (value == target) { count++; } } return count; } }
Built-in CountingGood

Let the library count: a stream filter in Java, list.count in Python, std::count in C++ and a filter in JavaScript. They all make the same single pass. C has no built-in, so it keeps the loop.

TimeO(n)
SpaceO(1)
class Solution { public int countOccurrences(int[] nums, int target) { return (int) Arrays.stream(nums).filter(value -> value == target).count(); } }

Related Problems