Smallest Number in Infinite Set
Keep a set of every positive integer that hands out its smallest number and takes numbers back.
Write a class whose object starts out holding every positive integer: 1, 2, 3 and so on, without end. It has two methods. popSmallest()addBack(num)numnum
Example 1
Output: 1, 2, 3, 1, 4, 5
Explanation: addBack(2) does nothing because 2 was never removed.
The Idea
Think of a roll of numbered tickets, starting at 1. popSmallestaddBack
Walk through Example 1 with that roll. The first call, addBack(2)addBack(1)
The catch is that the set never ends. No list or array can hold every positive integer, so how can an object store this set at all?
Look at the picture below, which shows the set right after addBack(1)nextnext
The only numbers that need storing one by one are the ones added back, such as the 1 marked added back. Each of them sits below nextnext
Solution Approach
Turning that idea into code means settling three things: where the added-back numbers are kept, which part popSmallest
Keeping the added-back numbers
What does popSmallestaddBackpopSmallest
A heap avoids that scan. It is a structure that keeps its smallest value on top, so it can always hand that value out first. If 4 and then 2 are added to it, taking from the top gives 2 and then 4. Adding a number and taking the top one each take O(log m) steps, not m.
Java provides a heap as PriorityQueuejava.utilComparator.naturalOrder()addpoll
Heap first, then the counter
Where should popSmallestnextnextnext
For the same reason, addBack(num)numnextaddBack(2)next
Stopping a number going in twice
What if the same number is added back twice? A set holds each number once, but a PriorityQueuePriorityQueue.containsHashSet
Optional: one TreeSet instead
A TreeSetaddBackaddpopSmallestpollFirstHashSet
Java Solution
The class has five parts, one for each piece of the approach:
: the counter. Every number fromnext upward is still in the set. It starts at 1.next : the min-heap, aaddedBack built withPriorityQueue , holding the numbers added back belowComparator.naturalOrder() .next : ainHeap with the same numbers asHashSet , so a number never goes into the heap twice.addedBack : polls the heap if it has anything, and otherwise returnspopSmallest and moves it up by one.next : addsaddBack to bothnum andinHeap , but only if it is belowaddedBack and not already waiting.next returnsinHeap.add for a number it already holds.false
The main
import java.util.Comparator;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Set;
public class SmallestNumberInInfiniteSet {
private int next = 1; // every number from next upward is in the set
private final PriorityQueue<Integer> addedBack =
new PriorityQueue<>(Comparator.naturalOrder()); // min-heap: smallest on top
private final Set<Integer> inHeap = new HashSet<>(); // numbers waiting in the heap
public int popSmallest() {
if (!addedBack.isEmpty()) { // anything added back is smaller than next
int smallest = addedBack.poll();
inHeap.remove(smallest);
return smallest;
}
return next++; // hand out next, then move it up by one
}
public void addBack(int num) {
if (num < next && inHeap.add(num)) { // num >= next is still in the set
addedBack.add(num);
}
}
public static void main(String[] args) {
SmallestNumberInInfiniteSet set = new SmallestNumberInInfiniteSet();
set.addBack(2); // 2 was never removed: nothing happens
System.out.print("Example 1: " + set.popSmallest() + ", " + set.popSmallest()
+ ", " + set.popSmallest());
set.addBack(1);
System.out.println(", " + set.popSmallest() + ", " + set.popSmallest()
+ ", " + set.popSmallest());
SmallestNumberInInfiniteSet twice = new SmallestNumberInInfiniteSet();
twice.popSmallest();
twice.popSmallest();
twice.addBack(1);
twice.addBack(1); // the same number added back twice
System.out.println("addBack(1) twice: " + twice.popSmallest() + ", "
+ twice.popSmallest());
SmallestNumberInInfiniteSet order = new SmallestNumberInInfiniteSet();
for (int i = 0; i < 5; i++) {
order.popSmallest(); // removes 1 to 5
}
order.addBack(4);
order.addBack(2);
System.out.println("addBack(4), addBack(2): " + order.popSmallest() + ", "
+ order.popSmallest() + ", " + order.popSmallest());
}
}
Running it prints:
Example 1: 1, 2, 3, 1, 4, 5
addBack(1) twice: 1, 3
addBack(4), addBack(2): 2, 4, 6
The first line matches Example 1: 1, 2, 3, then the returned 1, then 4 and 5 from the counter. On the second line, 1 was added back twice, yet only one 1 comes out, and the next pop moves on to 3. The third line starts after five pops, with next
The inHeap1, 1
Complexity
Each call does at most one heap step and one hash set step, and the infinite run of numbers costs nothing because it is a single counter.
- Time: O(log m) per call, where m is the number of added-back numbers waiting, because
andpoll on a heap of m numbers each take about log m steps, and theadd check takes one step.inHeap - Space: O(m), because the heap and
both hold just the waiting numbers belowinHeap , never the numbers fromnext upward.next
How a heap keeps its smallest value on top is shown in