Skip to content

Instantly share code, notes, and snippets.

@ritik-agrawal
Created February 15, 2024 08:45
Show Gist options
  • Save ritik-agrawal/d94cccab4a7d938f8082e57588dc2f40 to your computer and use it in GitHub Desktop.
Save ritik-agrawal/d94cccab4a7d938f8082e57588dc2f40 to your computer and use it in GitHub Desktop.
class RecentCounter {
List<Integer> queue;
int head;
int tail;
public RecentCounter() {
this.queue = new ArrayList<Integer>();
this.head = -1;
this.tail = -1;
}
public int ping(int t) {
add(t);
remove(t);
return (tail - head) + 1;
}
private void add(int t){
if (queue.size() == 0){
head++;
}
queue.add(t);
tail++;
}
private void remove(int t){
var low = t - 3000;
while (
(head <= tail) &&
(low >= 0) &&
(queue.get(head) < low)
){
head++;
}
}
}
@ritik-agrawal
Copy link
Author

ritik-agrawal commented Feb 15, 2024

Leetcode

Link: https://leetcode.com/problems/number-of-recent-calls/description/?envType=study-plan-v2&envId=leetcode-75

Achievement

  • The above uses queue logic to solve the problem.
  • All the other Solutions found in the solutions section have the same runtime.
  • The above solution beats 70% of the total submissions with a runtime value of 21 ms.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment