Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Start free
Sliding Window API Rate Limiter
00:00
5 left

Sliding Window API Rate Limiter

MediumPython

Problem

A company wants to protect an internal API endpoint used by backend services from bursts of traffic. Implement a per-user sliding window rate limiter that decides whether each request should be allowed.

Given a list of request events sorted by non-decreasing timestamp, determine for each event whether it is accepted under the rule: a user may make at most limit requests in any rolling interval of window_size seconds, inclusive of the current timestamp.

Formal Specification

Implement a function:

  • Input: requests: List[List[int]], where each element is [timestamp, user_id]
  • Input: limit: int
  • Input: window_size: int
  • Output: List[bool], where result[i] is True if requests[i] is allowed, otherwise False

A request at time t counts all previously accepted requests for the same user with timestamp >= t - window_size + 1 and <= t.

Constraints

  • 1 <= len(requests) <= 2 * 10^5
  • 1 <= limit <= 10^5
  • 1 <= window_size <= 10^9
  • 0 <= timestamp <= 10^9
  • 1 <= user_id <= 10^9
  • requests is sorted by non-decreasing timestamp

Function Signature

def rate_limiter(requests, limit, window_size):
Interviewer

Whenever you're ready, walk me through your approach or go straight to the code. The requirements are in the Question tab.

Sign up free to run or submit. Log in
Code
Sign up free to run your code. Your draft is saved.Run with a free accountLog inLn 2
Run your code to see test output here.