Data Structures & Algorithms Queues & Deques
💡
Exercise 78

Number of Recent Calls 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

Implement a RecentCounter that counts the number of requests made within the last 3000 milliseconds.

counter = RecentCounter() counter.ping(1) # 1 request in [1-3000, 1] → but range starts at max(0,1-3000)=0 # Requests in range: [1] → return 1 counter.ping(100) # Requests in [-2900, 100] → [1, 100] → return 2 counter.ping(3001) # Requests in [1, 3001] → [1, 100, 3001] → return 3 counter.ping(3002) # Requests in [2, 3002] → [100, 3001, 3002] → return 3

A queue is perfect here:

  • Add each new timestamp to the queue
  • Remove timestamps that are older than t - 3000 from the front
  • Return the length of the queue
  • Since timestamps are always increasing, old ones are always at the front

The queue naturally maintains the sliding window of valid timestamps.

📋 Instructions
Implement the RecentCounter class. Test with ping(1), ping(100), ping(3001), ping(3002) and print each result.
Use a deque. In ping(t), append t, then while q[0] < t - 3000, popleft(). Return len(q).
🧪 Test Cases
Input
counter.ping(1)
Expected
1
Test case 1
Input
counter.ping(100)
Expected
2
Test case 2
Input
counter.ping(3001)
Expected
3
Test case 3
Input
counter.ping(3002)
Expected
3
Test case 4
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.