Smallest Number in Infinite Set
Problem Statement
Picture the set of all positive integers: 1, 2, 3, and so on. It never runs out. Build a class SmallestInfiniteSet that starts with every positive integer in it.
popSmallest()removes the smallest number still in the set and returns it.addBack(num)putsnumback into the set. Ifnumis already in the set, nothing happens.
A series of popSmallest() and addBack(num) calls on a fresh set.
For each popSmallest() call, the number it removed. addBack returns nothing.
addBack(2) does nothing, because 2 is still in the set. The first three pops remove 1, 2 and 3. Then addBack(1) puts 1 back, so the next pop returns 1. After that the set continues from 4, so the last two pops return 4 and 5.
After three pops the set holds 4, 5, 6, and so on. The second addBack(2) is ignored because 2 is already waiting to come back. So 2 comes out only once, and the next pop skips straight to 4.
- • 1 ≤ num ≤ 1000
- • At most 1000 calls will be made in total to popSmallest and addBack
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Boolean array of removed numbers; popSmallest scans from 1 for the first one still in the set
std::set holding every number still in the set; the smallest is begin()
A counter covers every never-removed number; a min-heap and a hash set hold only the added-back ones
Keep taken[x] for every number from 1 to 1000. popSmallest scans from 1 and stops at the first number that is not taken, marks it taken, and returns it. addBack(num) clears its flag.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Heap — Top K translate into production architectures and low-level memory mechanics.