# The Tally Counter

> How many times does a single guest show up to the party?

Canonical URL: <https://datadriven.io/problems/the_tally_counter>

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a list of integers and a target, return the count of occurrences of target. Do not use list.count().

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **basic loop mechanics** and the ability to implement a trivial built-in from scratch. It probes whether a candidate can write a clean counting loop without relying on `list.count()`.

---

### Break down the requirements

#### Step 1: Initialize a counter to zero

The counter tracks how many times the target appears.

#### Step 2: Iterate and compare each element to the target

Increment the counter when a match is found.

---

### The solution

**Linear scan with equality check**

```python
def count_occurrences(nums: list, target: int) -> int:
    count = 0
    for num in nums:
        if num == target:
            count += 1
    result = count
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n) for a single pass through the list.
> 
> **Space:** O(1). Only one integer counter is used.

> **Interviewers Watch For**
>
> Even on trivial problems, clean variable naming and structure matter. Using `count` as both the counter variable name and avoiding shadowing the built-in `count` method shows awareness.

> **Common Pitfall**
>
> Using `list.count()` when the prompt explicitly says not to. This is a test of implementation ability, not API knowledge.

---

## Common follow-up questions

- What if the list was sorted? Could you do better than O(n)? _(Tests binary search for the first and last occurrence, giving O(log n).)_
- What if you needed to count multiple targets at once? _(Tests using a dict to accumulate counts for each target in one pass.)_
- What if elements were floating-point and you needed approximate matching? _(Tests using an epsilon tolerance: `abs(num - target) < epsilon`.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_tally_counter)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.