Count the orders before each prediction in Python
Given sorted order timestamps for one store and sorted prediction timestamps, return the number of orders in the 30 minutes before each prediction. An order exactly 30 minutes old counts. An order at the prediction timestamp does not.
Keep two indices into the order list. Advance the end index to the first order at or after the prediction time, then advance the start index past expired orders. The gap between them gives the count. Each index moves forward at most once per order, so the total time is O(n + m) for n orders and m predictions, with O(1) extra space excluding the output.
If input arrives out of order, clarify whether the count should reflect what was known at checkout. Sorting replay data by event time alone can include records that had yet to arrive. Capture the prompt in Hiintly, ask that follow-up aloud and compare the resulting approach with your own tests. The Python interview guide has more practice with written prompts and edge cases.
def prior_order_counts(order_times, prediction_times, window=30):
# Both inputs are sorted, and times are in minutes.
start = end = 0
counts = []
for prediction_time in prediction_times:
while end < len(order_times) and order_times[end] < prediction_time:
end += 1
window_start = prediction_time - window
while start < end and order_times[start] < window_start:
start += 1
counts.append(end - start)
return counts
assert prior_order_counts([0, 20, 30, 61], [30, 31, 62]) == [2, 2, 1]