Advertisement

Number of Recent Calls - LeetCode 933 Solution

Number of Recent Calls - Complete Solution Guide

Number of Recent Calls is LeetCode problem 933, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

You have a RecentCounter class which counts the number of recent requests within a certain time frame. Implement the RecentCounter class: RecentCounter() Initializes the counter with zero recent requests. int ping(int t) Adds a new request at time t , where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t -

Detailed Explanation

The problem asks us to design a `RecentCounter` class that counts the number of recent calls within a 3000ms time frame. The `ping(t)` method adds a new request at time `t` and returns the number of requests that occurred within the range `[t - 3000, t]`. The input `t` is guaranteed to be strictly increasing for each call to `ping`.

Solution Approach

The solution utilizes a queue (or a dynamically sized array in the C implementation) to store the incoming requests. Each time `ping(t)` is called, the new request `t` is added to the queue. Then, the algorithm iterates through the queue, removing any requests that are older than `t - 3000`. The remaining elements in the queue represent the recent requests within the desired time frame. The size of the queue is then returned.

Step-by-Step Algorithm

  1. Step 1: Initialize a queue (or dynamic array in C) to store requests.
  2. Step 2: In the `ping(t)` method, add the new request `t` to the queue.
  3. Step 3: While the queue is not empty and the oldest request (front of the queue) is older than `t - 3000`, remove the oldest request from the queue.
  4. Step 4: Return the current size of the queue, representing the number of recent requests.

Key Insights

  • Insight 1: The strictly increasing nature of `t` allows us to maintain a sorted list of requests and efficiently remove outdated requests from the beginning.
  • Insight 2: A queue is a natural choice to store the requests since we want to process them in a FIFO (First-In, First-Out) manner, allowing easy removal of elements outside the 3000ms window.
  • Insight 3: For the C implementation, a manual implementation is necessary as C does not have built-in queue. To optimize the ping operation in C, binary search can be used to find the number of requests within the given time range [t-3000,t]. This can significantly improve time complexity when the number of requests become very large.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(n)

Topics

This problem involves: Design, Queue, Data Stream.

Companies

Asked at: Affirm, Databricks, Roblox.