Every Trace
A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L3
Problem
A monitoring feed records one reading per slot. You're auditing for a specific value: return the slots where that value appears, earliest first.
It is in there somewhere. Where exactly?
Example 1
Input:
target = 20, readings = [10,20,30,20,40,20]
Output:
[1,3,5]
Example 2
Input:
target = 3, readings = [1,2,3,4,5]
Output:
[2]
Worked solution and explanation
What this really is
Under the audit-log costume this is just 'give me every index where the value matches', and the tell is that people reach for list.index out of habit. It hands back the FIRST hit and nothing else, so the moment the target repeats you have silently dropped positions; call it in a loop to find the rest and you re-scan from the front each time, turning an O(n) walk into O(n^2). The skill being probed is walking position and value together and collecting as you go, plus not forgetting that 'nothing matched' is a real, empty answer.
Break down the requirements
Step 1: Walk with the index in hand
Use enumerate (or range(len(readings))) so each step gives you both the position and the value at once.
Step 2: Keep every position that matches
Compare each reading to the target with == and append the index when they match. Because you scan left to right, the collected indices are already ascending.
The solution
def index_of_all(readings, target):
result = []
for i, value in enumerate(readings):
if value == target:
result.append(i)
return resultCommon follow-up questions
- What if the feed is sorted and you only need the range of matching positions? (Tests binary search for first and last occurrence using bisect.)
- How would you return the positions of every reading matching a predicate instead of a fixed value? (Tests generalizing from equality to a callable filter function.)
- What if the feed is enormous and you want to stream positions one at a time? (Tests a generator-based approach that yields positions lazily.)