Today, I’d like to share another really cool programming problem. This problem is Editor from the 2015 Baltic Olympiad in Informatics.
Here’s a quick summary of the problem: You’ve invented a text editor where there are 2 operations: edit and undo. Each operation has a level. An edit changes the editor state (initially 0) to some new state. An undo of level $L$ undoes the most recent operation with level strictly less than $L$. Note that an undo can undo a previous undo. Each edit has level 0 and the user determines the level of each undo. You’re now given a sequence of $N \leq 10^5$ operations. For each operation, you want to know the editor state directly after you apply it.
For example, we can have the following sequence of operations (E means edit; U means undo):
The official solution is a persistent trie of some sorts, but it’s long and complicated. Instead, I’ll present an elegant binary lifting solution.
I’ll focus on undo operations in this post, since nothing really happens with edit operations other than outputting the answer.
For 3 operations $X$, $Y$, $Z$ in order, if $Y$ can’t undo $X$ and $Z$ can’t undo $Y$, then $Z$ can’t undo $X$.
This observation is pretty obvious and doesn’t seem very helpful at first, but it will become useful later on.
Before we move on though, view each operation as a node in a graph. If $Y$ undoes $X$, draw an edge between $Y$ and $X - 1$ and let $P_Y = X - 1$.
Notice how the answer for $Y$ is simply the answer for $P_Y$. Additionally, our graph is a forest.
If $Y$ can’t undo $X$, then $Y$ can’t undo any operation in the range $(P_X, X]$.
This is because $P_X + 1$ is the most recent active operation $X$ could undo. The states of the operations in the range $(P_X, X]$ also remain unchanged after applying operation $X$, so by observation 1, this is true. (This still holds when we undo some operations.)
By observation 2, the operation we undo must lie on some path from the most recent operation upwards!
We essentially want the most recent operation with level strictly less than the current undo. We can use suffix minimums and binary lifting to find this operation.
The time complexity is $O(N \log N)$ and this gets us 100 points.