AlgoMaster Logo
AlgoMasterResume Long Polling with a Cursormedium

Resume Long Polling with a Cursor

medium

Long polling is safe across reconnect gaps only when the client sends a stable cursor and the server reads durable event history before waiting. An event that arrived between requests must still be found by the next request.

Design a LongPollServer class:

  • LongPollServer(int[] eventIds, int[] arrivalTimes) stores an immutable event history. IDs are strictly increasing and arrival times are non-decreasing.
  • int poll(int afterId, int openedAt, int timeout) returns the first event whose ID is greater than afterId when it is available no later than openedAt + timeout; otherwise it returns -1.

Events that arrived before openedAt are persisted and return immediately. An event arriving exactly at the deadline is included. Polling does not consume history, so separate clients may receive the same event.

Example 1:

Input:

Output:

Explanation: Event 43 arrives before the first deadline of 16. Event 44 misses the second deadline but arrives exactly at the third deadline of 18.

Example 2:

Input:

Output:

Explanation: Stored events are checked before waiting. Polling after the newest ID has no candidate.

Constraints

  • 0 <= eventIds.length == arrivalTimes.length <= 10^5
  • Event IDs are strictly increasing integers.
  • Arrival times are non-decreasing and between 0 and 10^9.
  • -1 <= afterId <= 10^9
  • 0 <= openedAt, timeout <= 10^9
  • At most 10^5 calls are made to poll.
Hints

Loading...
CallReturns
new LongPollServer([41,42,43,44], [0,5,12,18])null
poll(42, 6, 10)43
poll(43, 13, 3)-1
poll(43, 17, 1)44

Event 43 arrives before the first deadline of 16. Event 44 misses the second deadline but arrives exactly at the third deadline of 18.

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