08. Count Occurrences of a Target
Find how many times a given target value appears within an array.
How It Works & Algorithmic Design
Unlike Linear Search (which returns early upon finding the first match), counting occurrences requires inspecting every element in the array:
- Counter Initialization: Set
count = 0. - Exhaustive Pass: Iterate through every position from index $0$ to $n-1$.
- Match Accumulation: Increment
countby $1$ every timearr[i] === target. - Final Result: Return the accumulated total after the loop finishes.
Why This Approach Works Best
Because target matches may occur multiple times across the array, early termination cannot be used. Inspecting every element gives a time complexity of $O(n)$ and $O(1)$ space.
Example Walkthrough
Input:
[5, 2, 5, 8, 5, 1], Target: 5Target number 5 appears multiple times.
Trace:
5 (count=1) -> 2 -> 5 (count=2) -> 8 -> 5 (count=3) -> 1Evaluates all elements sequentially.
Output:
3Number 5 appears 3 times.
Answer: Count target frequencies
function countOccurrences(arr, target) {
let count = 0;
for (const value of arr) {
if (value === target) count++;
}
return count;
}💡 Scan the entire collection and increment a counter whenever the value matches.
Key Takeaways
- Requires an exhaustive scan over the entire collection.
- Runs in $O(n)$ time while keeping memory overhead at $O(1)$.
- Can be extended to count frequencies across multiple targets using a Hash Map.