« Competitive Programming in Haskell: modular arithmetic, part 2 » Data structure challenge: solutions

Data structure challenge: finding the rightmost empty slot

Posted on March 23, 2020
Tagged , , , , , , ,

Suppose we have a sequence of slots indexed from 1 to \(n\). Each slot can be either empty or full, and all start out empty. We want to repeatedly do the following operation:

We can also think of this in terms of two more fundamental operations:

The simplest possible approach would be to use an array of booleans; then marking a slot full is trivial, and finding the rightmost empty slot before index \(i\) can be done with a linear scan leftwards from \(i\). But the challenge is this:

Can you think of a data structure to support both operations in \(O(\lg n)\) time or better?

You can think of this in either functional or imperative terms. I know of two solutions, which I’ll share in a subsequent post, but I’m curious to see what people will come up with.

Note that in my scenario, slots never become empty again after becoming full. As an extra challenge, what if we relax this to allow setting slots arbitrarily?