Skip to content

Practice Smallest Number in Infinite Set

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#2336
LeetCode Problem

Smallest Number in Infinite Set

Problem Statement

SmallestInfiniteSet initially contains every positive integer. popSmallest() removes and returns its smallest member. addBack(num) restores num only if it is absent, without creating duplicates. Practice approach: Track the first number never popped and a min-heap plus membership set for restored smaller numbers. Pop from the heap when possible, otherwise advance the frontier. Ignore restoration at or beyond the frontier because those numbers already exist. Test adding an existing number and adding the same removed number twice.

Source: Smallest Number in Infinite Set on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["SmallestInfiniteSet","popSmallest","popSmallest","addBack","addBack","popSmallest","popSmallest"]
[[],[],[],[1],[1],[],[]]
Output
[null,1,2,null,null,1,3]
Explanation

Duplicate restoration of 1 creates only one entry; after it is popped, the next untouched value is 3.

Constraints

1 <= num <= 1000
At most 1000 total calls.

Related LeetCode Problems

Practice more problems similar to Smallest Number in Infinite Set.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.