AlgoMaster Logo
AlgoMasterSimulate a Queue Visibility Timeoutmedium

Simulate a Queue Visibility Timeout

medium

A distributed queue does not have to delete a message as soon as a consumer receives it. Instead, it can hide the message for a visibility timeout. If the consumer acknowledges the message, the broker deletes it. If the consumer crashes without acknowledging, the timeout expires and the message becomes available for redelivery.

In this exercise, one message is never acknowledged.

Design a VisibilityTimeoutQueue class:

  • VisibilityTimeoutQueue(int timeout) creates a queue whose message starts visible at timestamp 0.
  • boolean receive(int timestamp) attempts to receive the message at timestamp.

A receive succeeds when the message is visible. A successful receive returns true and hides the message until timestamp + timeout. A receive before that time returns false and must not change the current visibility deadline.

Calls use non-decreasing timestamps. When timestamp is exactly the visibility deadline, the timeout has expired and the receive succeeds.

Example 1:

Input:

Output:

Explanation: The receive at 0 hides the message until 10, so the attempt at 5 fails. At 20 the message is visible and becomes hidden until 30, so the attempt at 25 fails.

Example 2:

Input:

Output:

Explanation: Every receive occurs exactly when the preceding timeout expires. The visibility boundary is inclusive, so every call succeeds.

Constraints

  • 1 <= timeout <= 10^9
  • 0 <= timestamp <= 10^9
  • Calls to receive use non-decreasing timestamps.
  • The message is never acknowledged or deleted.
  • At most 10^5 calls are made to receive.
Hints

Loading...
CallReturns
new VisibilityTimeoutQueue(10)null
receive(0)true
receive(5)false
receive(20)true
receive(25)false

The receive at 0 hides the message until 10. The attempt at 5 fails. The receive at 20 hides it until 30, so the attempt at 25 fails.

Run checks these cases. Submit also runs a larger hidden set.