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() removes the smallest number in the set and returns it. addBack(num) puts num back into the set, and does nothing if num is already there.

Example 1
Input: addBack(2), popSmallest(), popSmallest(), popSmallest(), addBack(1), popSmallest(), popSmallest(), popSmallest()
Output: 1, 2, 3, 1, 4, 5
Explanation: addBack(2) does nothing because 2 was never removed.
Solution

The Idea

Think of a roll of numbered tickets, starting at 1. popSmallest tears off the lowest ticket and hands it out. addBack takes a used ticket back, so it can be handed out again.

Walk through Example 1 with that roll. The first call, addBack(2), changes nothing: ticket 2 is still on the roll. The next three calls tear off 1, 2 and 3. Then addBack(1) returns ticket 1, so the next pop gives 1 again, not 4. After that the roll carries on with 4 and 5.

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). The numbers 2 and 3, marked popped, are gone. From 4 upward nothing has been touched, and that run of numbers never has a gap. So a single number, next, describes all of it: every number from next upward is still in the set.

After three popSmallest calls and addBack(1): 1 is back and kept in a min-heap, 2 and 3 are popped, and every number from next = 4 upward is still in the set, stored as one counter.

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 next, because a number at or above next was never removed. So the infinite set becomes one counter plus a short collection of returned numbers.

Solution Approach

Turning that idea into code means settling three things: where the added-back numbers are kept, which part popSmallest reads first, and how to stop a number going in twice. After those comes an optional shortcut that uses a single sorted set instead.

Keeping the added-back numbers

What does popSmallest need from that collection? It needs the smallest number in it, quickly. The simple way is a list: addBack appends, and popSmallest scans the whole list for the smallest. With m numbers waiting, every pop then reads all m of them.

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 PriorityQueue, in java.util. Built with Comparator.naturalOrder(), it orders numbers from small to large, which makes it a min-heap. add puts a number in, and poll removes and returns the smallest.

Heap first, then the counter

Where should popSmallest look first? Every number in the heap is below next, so when the heap has anything, its top is the smallest number in the whole set. Only when the heap is empty is next the answer, and next then moves up by one.

For the same reason, addBack(num) ignores any num at or above next. That is what happens to addBack(2) in Example 1, where next is still 1.

Stopping a number going in twice

What if the same number is added back twice? A set holds each number once, but a PriorityQueue happily takes copies. PriorityQueue.contains could check first, but it looks through the whole queue. A HashSet beside the heap, holding the same numbers, answers that check in one step.

Optional: one TreeSet instead

A TreeSet keeps its numbers sorted and refuses copies on its own. With it, addBack is one add and the heap step of popSmallest is one pollFirst, both O(log m). The code below keeps the heap and HashSet pair, which does the same job and shows how a heap is put to work.

Java Solution

The class has five parts, one for each piece of the approach:

  • next: the counter. Every number from next upward is still in the set. It starts at 1.
  • addedBack: the min-heap, a PriorityQueue built with Comparator.naturalOrder(), holding the numbers added back below next.
  • inHeap: a HashSet with the same numbers as addedBack, so a number never goes into the heap twice.
  • popSmallest: polls the heap if it has anything, and otherwise returns next and moves it up by one.
  • addBack: adds num to both inHeap and addedBack, but only if it is below next and not already waiting. inHeap.add returns false for a number it already holds.

The main method runs Example 1, adds the same number back twice, and adds back two numbers in the wrong order to see the heap sort them.

Java
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:

Output
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 at 6. The numbers 4 and 2 went in that order, but the heap hands out 2 first, then 4, and only then 6.

The inHeap set is easy to leave out, since the heap seems to hold the numbers already. Without it, the second line's test prints 1, 1: the heap keeps both copies, and the set hands out the same number twice.

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 poll and add on a heap of m numbers each take about log m steps, and the inHeap check takes one step.
  • Space: O(m), because the heap and inHeap both hold just the waiting numbers below next, never the numbers from next upward.

How a heap keeps its smallest value on top is shown in Heap Introduction.