The Tally Counter
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- 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().
How many times does a single guest show up to the party?
Example 1
Input:
nums = [1,2,3,2,1], target = 2
Output:
2
Example 2
Input:
nums = [5,5,5], target = 5
Output:
3
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
def count_occurrences(nums: list, target: int) -> int:
count = 0
for num in nums:
if num == target:
count += 1
result = count
return resultCommon 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`.)