Understand what the interviewer is asking for by using test cases and questions about the problem.
k
.time_points
and an integer k
.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use a dictionary to store the last seen index of each event ID, and check if the difference between the current index and the last seen index is within the allowed range.
1) Initialize a dictionary `last_seen` to store the last seen index of each event ID.
2) Iterate over `time_points`:
- For each event, check if it has been seen before and if the difference in indices is within `k`.
- If so, return `True`.
- Update the last seen index of the event.
3) If no anomalies are found, return `False`.
⚠️ Common Mistakes
def detect_temporal_anomaly(time_points, k):
# Dictionary to store the last seen index of each event ID
last_seen = {}
for i, event in enumerate(time_points):
if event in last_seen:
if i - last_seen[event] <= k:
return True
# Update the last seen index of the event
last_seen[event] = i
return False