08. Count Occurrences of a Target

Difficulty:EasyPattern:Counting PassTime:O(n)Space:O(1)

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:

  1. Counter Initialization: Set count = 0.
  2. Exhaustive Pass: Iterate through every position from index $0$ to $n-1$.
  3. Match Accumulation: Increment count by $1$ every time arr[i] === target.
  4. 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: 5
Target number 5 appears multiple times.
Trace: 5 (count=1) -> 2 -> 5 (count=2) -> 8 -> 5 (count=3) -> 1
Evaluates all elements sequentially.
Output: 3
Number 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.