Rate Limiter - Problem

Design and implement a rate limiter that controls the rate of requests using the sliding window algorithm. The rate limiter should allow exactly N requests per time window of W seconds.

Your rate limiter must support:

  • allow(timestamp) - Returns true if the request at the given timestamp is allowed, false otherwise
  • The sliding window should continuously move based on the current timestamp
  • Only requests within the current time window should be counted

The sliding window algorithm maintains a window that slides forward in time, removing old requests that fall outside the current window before deciding whether to allow new requests.

Input & Output

Example 1 — Basic Rate Limiting
$ Input: maxRequests = 2, windowSize = 10, requests = [1, 2, 15, 16]
Output: [true, true, true, false]
💡 Note: First two requests (t=1, t=2) are allowed. At t=15, window [5-15] only contains t=15, so allowed. At t=16, window [6-16] contains t=15 and t=16, reaching limit of 2.
Example 2 — Window Sliding
$ Input: maxRequests = 3, windowSize = 5, requests = [1, 3, 5, 7, 9]
Output: [true, true, true, true, false]
💡 Note: Requests at t=1,3,5 fill the limit. At t=7, window [2-7] contains t=3,5,7 (3 requests). At t=9, window [4-9] contains t=5,7 so t=9 would make it 3, but limit is 3, so rejected.
Example 3 — All Requests Allowed
$ Input: maxRequests = 5, windowSize = 3, requests = [1, 5, 10]
Output: [true, true, true]
💡 Note: Each request is far enough apart that the sliding window never contains more than 1 request at a time, well under the limit of 5.

Constraints

  • 1 ≤ maxRequests ≤ 100
  • 1 ≤ windowSize ≤ 1000
  • 1 ≤ requests.length ≤ 1000
  • 1 ≤ requests[i] ≤ 106
  • requests are sorted in non-decreasing order

Visualization

Tap to expand
INPUTALGORITHMRESULTRate Limiter Config:Max Requests: 2Window Size: 10sRequest Sequence:t=1t=2t=15t=16Process each request throughsliding window algorithmSliding Window Steps:1Remove expired requests2Count current window size3Allow if under limit4Add to queue if allowedQueue State Example:At t=16: Window [6-16]Queue: [15, 16]Size: 2 = Max: 2 → REJECTDecision Results:Request Results:t=1: ✓ true (first request)t=2: ✓ true (second allowed)t=15: ✓ true (new window)t=16: ✗ false (limit hit)Final Output:[true,true,true,false]Key Insight:The sliding window maintains only recent requests within the time boundary,automatically discarding old entries and providing O(1) amortized performance.TutorialsPoint - Rate Limiter | Sliding Window Algorithm
Asked in
Google 45 Amazon 38 Microsoft 32 Netflix 28
34.5K Views
High Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen