Skip to content

Commit fc3614a

Browse files
Create LeetCode_362_Hit_Counter_Medium.ts
1 parent 37d9427 commit fc3614a

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* Probleml: Design a hit counter that keeps track of the total number of hits in the last 5 minutes.
3+
* Solution: Uses a bounded buffer of exactly 300 seconds to keep track of the number of hits in that particular second. Each second bucket
4+
* will keep track of the hits incurred in that particular second. Along with that, it will also keep track of the timestamp associated
5+
* with each bucket. This is required so that, when we round over and use the same buckets, we can correlate which time we are looking at
6+
* with respect to a bucket.
7+
*/
8+
class HitCounter {
9+
10+
hits: number[]
11+
times: number[]
12+
13+
constructor() {
14+
this.hits = Array(300).fill(0)
15+
this.times = Array(300).fill(0);
16+
}
17+
18+
hit(timestamp: number): void {
19+
const pos = timestamp % 300;
20+
if (this.times[pos] !== timestamp) {
21+
// Starting over, the last logged timestamp was before 5 mts.
22+
this.hits[pos] = 1
23+
this.times[pos] = timestamp
24+
} else {
25+
this.hits[pos]++
26+
}
27+
}
28+
29+
getHits(timestamp: number): number {
30+
let count = 0
31+
for (let idx = 0; idx < 300; idx++) {
32+
if (timestamp - this.times[idx] < 300) {
33+
// This existing time tick hit value is obselete and should not be added.
34+
count += this.hits[idx]
35+
}
36+
}
37+
38+
return count;
39+
}
40+
}
41+
42+
/**
43+
* Your HitCounter object will be instantiated and called as such:
44+
* var obj = new HitCounter()
45+
* obj.hit(timestamp)
46+
* var param_2 = obj.getHits(timestamp)
47+
*/

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy