Skip to content

Commit 74236eb

Browse files
committed
feat: Solving "Number of recent calls" (LeetCode | #933 | Easy)
1 parent 33d2769 commit 74236eb

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

stacks-queues/number-recent-calls.js

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/**
2+
* LeetCode | #933 | Easy
3+
*
4+
* You have a RecentCounter class which counts the number of recent requests within a certain time frame.
5+
*
6+
* Implement the RecentCounter class:
7+
* - RecentCounter() Initializes the counter with zero recent requests.
8+
* - int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns
9+
* the number of requests that has happened in the past 3000 milliseconds (including the new request).
10+
* Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t].
11+
*
12+
* It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.
13+
*
14+
* Constraints:
15+
* - 1 <= t <= 10^9
16+
* - Each test case will call ping with strictly increasing values of t.
17+
* - At most 10^4 calls will be made to ping.
18+
*
19+
*/
20+
21+
22+
/**
23+
* Solution 1 (slowest -- resembling a queue with "shift" which is slow)
24+
* Time Complexity: O(n) - Space complexity: ?
25+
*/
26+
27+
const RecentCounter = function () {
28+
this.recentReqsQueue = [];
29+
};
30+
31+
/**
32+
* @param {number} t
33+
* @return {number}
34+
*/
35+
RecentCounter.prototype.ping = function (t) {
36+
this.recentReqsQueue.push(t);
37+
const minRangeVal = Math.max(t - 3000, 0);
38+
39+
while (this.recentReqsQueue.length > 0 && this.recentReqsQueue[0] < minRangeVal) {
40+
this.recentReqsQueue.shift();
41+
}
42+
43+
return this.recentReqsQueue.length;
44+
};
45+
46+
/**
47+
* Solution 2 (fastest -- resembling a queue behaviour by using a pointer)
48+
* Time Complexity: O(n) - Space complexity: O(n)
49+
*/
50+
51+
const RecentCounter2 = function () {
52+
this.i = 0;
53+
this.recentReqsQueue = [];
54+
};
55+
56+
/**
57+
* @param {number} t
58+
* @return {number}
59+
*/
60+
RecentCounter2.prototype.ping = function (t) {
61+
this.recentReqsQueue.push(t);
62+
const minRangeVal = Math.max(t - 3000, 0);
63+
64+
while (this.recentReqsQueue.length > 0 && this.recentReqsQueue[this.i] < minRangeVal) {
65+
this.i++;
66+
}
67+
68+
return this.recentReqsQueue.length - this.i;
69+
};
70+
71+
/**
72+
* Your RecentCounter object will be instantiated and called as such:
73+
* var obj = new RecentCounter()
74+
* var param_1 = obj.ping(t)
75+
*/

0 commit comments

Comments
 (0)