Skip to content

Commit 3fc70a2

Browse files
Create LeetCode_362_Hit_Counter_1.ts
1 parent 3a48bf3 commit 3fc70a2

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
type Hit = {
2+
timestamp: number
3+
hits: number
4+
}
5+
6+
/**
7+
* Problem: Designing a hit counter which counts the total number of hits in the last 5 minutes.
8+
* Solution: Uses a queue to keep on appending the value of the hits at each request. We do this by using a queue. If the queue contains a value for the same timestamp,
9+
* we simply update it. If it does not contain, we increment it. While getting the values, we need to add all the values that are within 5 minutes of interval for counting
10+
* the results. Also, we need to trim all the values that were called before 5 minutes.
11+
*/
12+
class HitCounter {
13+
14+
hits: Hit[]
15+
16+
constructor() {
17+
this.hits = []
18+
}
19+
20+
hit(timestamp: number): void {
21+
const last = this.hits.length > 0 ? this.hits[this.hits.length - 1] : undefined
22+
if (last && last.timestamp === timestamp) {
23+
last.hits++
24+
} else {
25+
this.hits.push({
26+
timestamp,
27+
hits: 1
28+
});
29+
}
30+
}
31+
32+
getHits(timestamp: number): number {
33+
let pos = this.hits.length - 1
34+
let hitItem = this.hits[pos]
35+
let total = 0
36+
while(hitItem !== undefined && timestamp - hitItem.timestamp < 300) {
37+
total += hitItem.hits;
38+
pos--
39+
hitItem = this.hits[pos]
40+
}
41+
42+
if (pos > 0) {
43+
this.hits = this.hits.slice(pos + 1)
44+
}
45+
46+
return total;
47+
}
48+
}
49+
50+
/**
51+
* Your HitCounter object will be instantiated and called as such:
52+
* var obj = new HitCounter()
53+
* obj.hit(timestamp)
54+
* var param_2 = obj.getHits(timestamp)
55+
*/

0 commit comments

Comments
 (0)