Number of Recent Calls LeetCode Solution - The Coding Shala

Home >> LeetCode >> Number of Recent Calls

 In this post, we will learn how to solve LeetCode's Number of Recent Calls Problem and will implement its solution in Java.

Number of Recent Calls Problem

You have a RecentCounter class that 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 have happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t].
  • It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.

Example 1:
Input:
["RecentCounter", "ping", "ping", "ping", "ping"]
[[], [1], [100], [3001], [3002]]
Output:
[null, 1, 2, 3, 3]

Practice this problem on LeetCode.

LeetCode - Number of Recent Calls Java Solution

Approach 1

Using Queue.

Add new Ping into the queue and remove all the times that don't come in the range t-3000 to t. Return size of the queue.

Java Program: 

class RecentCounter {
    Queue<Integer> queue;

    public RecentCounter() {
        queue = new LinkedList<Integer>();
    }
    
    public int ping(int t) {
        queue.offer(t);
        int time = t - queue.peek();
        while(time > 3000) {
            queue.poll();
            time = t - queue.peek();
        }
        return queue.size();
    }
}

/**
 * Your RecentCounter object will be instantiated and called as such:
 * RecentCounter obj = new RecentCounter();
 * int param_1 = obj.ping(t);
 */


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala