Skip to content

Requests in the Last Window

Easy#queue#sliding-window~15 min

The mission

Problem

A service logs the arrival time of every request in milliseconds, and the times come in non-decreasing order. For each request, report how many requests, itself included, arrived during the last w milliseconds, that is, at a time strictly greater than its own time minus w. Return one count per request.

Examples

Input:  times = [0, 400, 900, 1000, 1400], w = 1000
Output: [1, 2, 3, 3, 3]
Why:    at 1000 the request from time 0 is exactly w old and no longer counts
Input:  times = [5, 5, 5], w = 1
Output: [1, 2, 3]
Why:    equal times all fall inside the same window
Input:  times = [], w = 50
Output: []
Why:    edge case, no requests

Hints

0 / 3

Target time
O(n)
Target space
O(n)

Constraints

  • times are in non-decreasing order

Stuck on the idea rather than the code? Queue Basics covers it.

Python 3Ctrl+Enter runs
Custom test case