LeetCode 75

Number of Recent Calls

Problem
LC 933
Topic
Queue
File
official75_LC933NumberOfRecentCalls.java
Path
pkg5leetcode/official75/official75_LC933NumberOfRecentCalls.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC933NumberOfRecentCalls.java
Approach
Queue evict calls older than t-3000.
Complexity
Time O(1) amortized, Space O(n)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC933NumberOfRecentCalls.java
1package pkg5leetcode.official75;2 3/*4 * Number of Recent Calls | LC 9335 * APPROACH: Queue evict calls older than t-3000.6 * COMPLEXITY: Time O(1) amortized, Space O(n)7 */8import java.util.*;9 10public class official75_LC933NumberOfRecentCalls {11    static class RecentCounter {12        Deque<Integer> q = new ArrayDeque<>();13 14        int ping(int t) {15            q.addLast(t);16            while (q.peekFirst() < t - 3000) q.pollFirst();17            return q.size();18        }19    }20 21    public static void main(String[] args) {22        RecentCounter rc = new RecentCounter();23        check(rc.ping(1) == 1, "case1");24        check(rc.ping(100) == 2, "case2");25        check(rc.ping(3001) == 3, "case3");26        check(rc.ping(3002) == 3, "case4");27        System.out.println("all tests passed");28    }29 30    static void check(boolean cond, String name) {31        if (!cond) throw new AssertionError("FAILED: " + name);32        System.out.println("  PASS " + name);33    }34}