๐Ÿšฆ

Rate Limiter

Allow at most N requests in any 10-second window โ€” the logic behind every API.

Project 11Advanced

๐Ÿงฉ Problem statement

Requests arrive at increasing times (in seconds). Allow at most LIMIT requests in any window of 10 seconds: a request at time T is allowed if fewer than LIMIT allowed requests happened in (T โˆ’ 10, T]. Show ALLOW or BLOCK for each request.

๐Ÿ“‹ Requirements

  • Time windows
  • Counters
  • State
  • Queue of timestamps

๐Ÿ“ฅ Inputs

  • LIMIT
  • REQUEST_TIMES: list of request times

๐Ÿ“ค Outputs

  • ALLOW / BLOCK per request

๐Ÿ“ Rules

  • Window: the last 10 seconds, (T โˆ’ 10, T]
  • Blocked requests donโ€™t count

๐Ÿšง Constraints

  • Times are in increasing order

๐Ÿงญ Suggested approach

  • Keep a queue of the times of allowed requests
  • Remove old times from the front
  • Allow if the queue has room

๐Ÿง  Required concepts

  • Queues
  • Loops
  • State
โœ๏ธ Pseudocode editor ยท dry-run tool ยท test cases

Design your solution here. Use Run to dry-run it step by step and Run tests to check it. Hints unlock one at a time โ€” try on your own first!

๐Ÿงช Edge cases to test

  • Requests exactly 10 seconds apart
  • LIMIT = 1
  • A burst of many requests at the same time

๐Ÿ“ˆ Complexity analysis

Each request is added and removed at most once: O(n) total. Memory O(LIMIT).

๐Ÿ“– Solution walkthrough (open after youโ€™ve tried!)

The queue holds the times of recent allowed requests, oldest at the front. Before judging a new request, times that have left the 10-second window are dropped from the front. If fewer than LIMIT remain, the request is allowed and its time is queued; otherwise itโ€™s blocked.

๐Ÿš€ Challenge extensions

  • A different limit per user (map of queues)
  • Report how long until the next request is allowed
  • A token-bucket version

โ† All projects