FastPrepDesign Hit Counter

Design Hit Counter

Nutanix logoNutanix● MediumFULLTIMEONSITE INTERVIEW

Problem statement

Build a counter that records website hits and reports how many happened in the last five minutes. Process the calls in order. The two calls are:

  • "hit": one hit happens at second timestamps[i]. Several hits can happen in the same second.
  • "getHits": report how many hits so far happened in the last 300 seconds. For a call at time t, count the hits from time t - 299 through time t, both included.

A call only sees the calls before it, so a hit that comes later in the list does not count, even if it has the same timestamp.

Return an array with one number for each "getHits" call, in order. A "hit" call adds nothing to the array.

Function

hitCounter(operations: String[], timestamps: int[]) → int[]

Examples

Example 1

operations = ["hit","hit","hit","getHits","hit","getHits","getHits"]timestamps = [1,2,3,4,300,300,301]return = [3,4,3]
  • At time 4, the window reaches back before the first second, so it holds the hits at 1, 2 and 3, and the count is 3.
  • At time 300, the window is 1 through 300 and also holds the new hit at 300, so the count is 4.
  • At time 301, the window is 2 through 301. The hit at 1 has left, so the count is 3.

Example 2

operations = ["hit","hit","hit","getHits","getHits","getHits"]timestamps = [5,5,5,5,304,305]return = [3,3,0]
  • Three hits happen in second 5. At time 5 the count is 3.
  • At time 304, the window is 5 through 304, so all three still count.
  • At time 305, the window is 6 through 305. All three leave together, so the count is 0.

Constraints

  • 1 <= operations.length <= 10000
  • timestamps.length == operations.length
  • Each operations[i] is "hit" or "getHits".
  • 1 <= timestamps[i] <= 2 * 10^9
  • timestamps never decreases: timestamps[i] <= timestamps[i + 1].

More Nutanix problems

See Nutanix hiring insights
Saved
public int[] hitCounter(String[] operations, int[] timestamps) {
    // Write your code here.
}
operations["hit","hit","hit","getHits","hit","getHits","getHits"]
timestamps[1,2,3,4,300,300,301]
expected[3,4,3]
Checking account…