Save 25%Black Friday: 25% off all plans — use code BLACKFRIDAY2026 at checkout. Ends Friday, Dec 4.Claim the deal

An infinite queue is a data structure that dynamically expands to hold an unlimited number of elements. Implement an infinite queue specifically for integers, supporting the following operations:

  • offer(int val): Add an integer to the tail of the queue.
  • int poll(): Removes and returns the integer at the front of the queue. If the queue is empty, returns -1.
  • int getRandom(): Returns a random integer from the queue. If the queue is empty, returns -1.

All operations must be implemented to run in O(1) time.

Constraints:

  • The number of operations will not exceed 105.
  • All integers are within the range [-109, 109].

Example 1:

Input: ["InfiniteQueue", "offer", "offer", "offer", "offer", "offer", "getRandom", "getRandom", "getRandom", "poll", "poll", "poll", "poll", "poll"] [[], [1], [2], [3], [4], [5], [], [], [], [], [], [], [], []]

Output: [null, null, null, null, null, null, 3, 1, 5, 1, 2, 3, 4, 5]

Explanation:

  • InfiniteQueue queue = new InfiniteQueue();
  • queue.offer(1); // Queue: [1]
  • queue.offer(2); // Queue: [1,2]
  • queue.offer(3); // Queue: [1, 2, 3]
  • queue.offer(4); // Queue: [1, 2, 3, 4]
  • queue.offer(5); // Queue: [1, 2, 3, 4, 5]
  • queue.getRandom(); // Return a ramdom number from 1 to 5
  • queue.getRandom();
  • queue.getRandom();
  • queue.poll(); // Return 1, Queue: [2, 3, 4, 5]
  • queue.poll(); // Return 2, Queue: [3, 4, 5]
  • queue.poll(); // Return 3, Queue: [4, 5]
  • queue.poll(); // Return 4, Queue: [5]
  • queue.poll(); // Return 5, Queue: []
  • queue.poll(); // Return -1

Accepted
861/1.6k
Acceptance Rate52.7%
Stdout
-