FastPrepQueue Mean Queries

Queue Mean Queries

Headlands Technologies logoHeadlands Technologies● EasyFULLTIMEPHONE SCREEN
Learn

Problem statement

Process a sequence of operations on an initially empty first-in, first-out queue of integers.

  • PUSH x appends integer x to the back of the queue.
  • POP removes the oldest value from the front. Every POP occurs when the queue is nonempty.
  • MEAN requests the arithmetic mean of the values currently in the queue. Its result is 0.0 when the queue is empty.

Return one floating-point result for each MEAN, in request order. PUSH and POP produce no result entries. A mean is the current sum divided by the current number of values; it must not use integer division.

Support each operation in constant amortized time. Returned values are compared with relative-or-absolute tolerance 10^-9.

Function

queueMeans(operations: String[]) → double[]

Examples

Example 1

operations = ["MEAN","PUSH 5","MEAN","PUSH 9","MEAN","POP","MEAN","POP","MEAN"]return = [0.0,5.0,7.0,9.0,0.0]

The requested queue states are [], [5], [5,9], [9], and []. Their means are 0, 5, 7, 9, and 0.

Example 2

operations = ["PUSH -2","PUSH 3","PUSH 3","MEAN","POP","MEAN","PUSH 0","MEAN"]return = [1.3333333333333333,3.0,2.0]

The first mean is (-2 + 3 + 3) / 3 = 4/3. Removing the oldest value leaves [3,3]. Appending 0 leaves [3,3,0].

Example 3

operations = ["PUSH 1","POP"]return = []

No MEAN request occurs, so the returned array is empty.

Constraints

  • 1 <= operations.length <= 2 * 10^5.
  • Each command is exactly POP, MEAN, or PUSH x with a signed decimal integer x.
  • -10^9 <= x <= 10^9.
  • Every POP removes a value from a nonempty queue.
  • All commands are valid. Use a signed 64-bit running sum.

More Headlands Technologies problems

See Headlands Technologies hiring insights
public double[] queueMeans(String[] operations) {
    // Write your code here.
}
operations["MEAN","PUSH 5","MEAN","PUSH 9","MEAN","POP","MEAN","POP","MEAN"]
expected[0.0,5.0,7.0,9.0,0.0]
Checking account…