• + 5 comments

    The editorial offers two solutions, one more efficient than the other. Neither are the most efficient. The more efficient one still traverses the collection twice and uses twice the space of the size of the collection till both traversals are finished.

    There is a way to solve this with a single traversal in constant space. It requires maintaining a queue which will never contain more than d elements. Each element in the queue will contain either a single value n or a double value n and n + d. Each value x in the input collection will either be the next value in the first element of the queue or a new singleton to be added to the end. Any elements at the front of the queue which were waiting for a value smaller than x can be discarded. Hence the queue will never be larger than d elements.

    I don't believe in posting complete solutions to discussion pages so I hope that's enough to help people think of a truly efficient solution.