A nice simple one!
You are given a finite sequence. Find the earliest pair of equal elements, if any (where "earliest" refers to the position of the second element of the pair), and collapse them and the interval of elements between them into a single copy of the repeated element. E.g. abcda -> a
. Repeat this operation until all elements are distinct, and return the resulting final sequence.
Note that the order of the collapsing operations matters.
(This arises in the construction of the "loop-erased random walk", which has important applications.)
Example
Input: abcbbcdeaeec
a[bcb]bcdeaeec
a(b)bcdeaeec
a[bb]cdeaeec
a(b)cdeaeec
[abcdea]eec
(a)eec
a[ee]c
a(e)c
Output: aec
Input/Output
You can assume that the input sequence is either a string of printable non-whitespace characters or a list (array, tuple, etc) of nonnegative integers (your choice). You can assume that it has at least 1 element. The output sequence should be in the same form as the input.
Test cases
x -> x
xxxx -> x
ioioioio -> io
1234321 -> 1
xyzxyzxyz -> xyz
123213132 -> 132
abcbbcdeaeec -> aec
This is code-golf, so the shortest solution in each language wins.
axbayb
cares whether you collapse a's first or b's. But this requires overlapping intervals, so the same one will be chosen whether you compare by their left or right endpoints. If this choice matters, then one interval is contained within the other, and so it should be safe to delete the inner one first or not, since the outer one will be deleted regardless. \$\endgroup\$