We have a group of objects, let’s call them Players. We can traverse through this group only with random order, e.g. there is no such thing as Players[0].
Each Player has a unique ID, with ID < len(Players). Player’s can be added and removed to the group. When a Player gets removed it will free his ID, and if a Player gets added it will acquire an ID.
If we want to add a new Player to Players we have to generate a new unique ID. What is the fastest way to generate such ID in O(1) space?
O(n log n) is possible with binary search. Start with a = 0 and b = n. The invariant is that there exists a free id in the interval [a, b). Repeat the following until b – a = 1: let m = a + floor((b – a) / 2), count the number of ids in [a, m) and in [m, b). If [a, m) has fewer than m – a ids, then set b = m. Otherwise, set a = m.