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:
readings = [10,20,30,20,40,20], target = 20
Output:
[1,3,5]
Example 2
Input:
readings = [1,2,3,4,5], target = 3
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 slots; 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 slot in hand
Use enumerate (or range(len(readings))) so each step gives you both the slot and the reading at once.
Step 2: Keep every slot that matches
Compare each reading to target with == and append the slot when they match. Because you scan left to right, the collected slots are already ascending, and an absent target simply leaves the list empty.
The solution
def index_of_all(readings, target):
positions = []
for slot, reading in enumerate(readings):
if reading == target:
positions.append(slot)
return positionsCommon follow-up questions
- What if the feed is sorted and you only need the range of matching slots? (Tests binary search for first and last occurrence using `bisect`.)
- How would you return the slots 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 slots one at a time? (Tests a generator-based approach that yields slots lazily.)