AlgoMaster Logo

Number of Recent Calls

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force with List

Intuition:

The problem requires us to count the number of calls within a sliding window of 3000 milliseconds. One straightforward approach is to maintain a list of timestamps and iterate over them to count how many fall within this range each time a new call is added.

Steps:

  1. Maintain a list to store each call received in increasing order of time.
  2. On each call to ping, calculate the time window [t - 3000, t].
  3. Iterate over the list and count how many timestamps fall within this window.

Code:

2. Optimized with Queue

Intuition:

Instead of iterating over all past calls, we can use a queue to efficiently add new timestamps and remove old ones that fall out of the sliding window, maintaining only the relevant timestamps within the queue.

Steps:

  1. Use a queue to store timestamps.
  2. On each call to ping, add the current timestamp to the queue.
  3. Remove timestamps from the front of the queue if they are older than the start of the sliding window [t - 3000].
  4. The size of the queue at any time will give the count of timestamps in the required range.

Code: