Is there any well-known algorithm (or obvious solution) for transforming a list from order A to order B using only push and remove operations? For instance, from a b c d to b c a d could be done using the following operations:
remove(a)
remove(d)
push(a)
push(d)
Or, from c b a to a b would be
remove(c)
remove(b)
push(b)
Or, from a c b to a c b d would be
push(d)
Here, push appends an element to the end of the list, and remove removes the element and shifts the subsequent elements so that the list is always in continuous state (no “empty slots”). Additionally there’s a condition that at any given moment the list may contain the same element only once. Therefore it seems sound to first do all removes in one bunch, and all pushes after that. The order of removes obviously doesn’t matter, but the order of pushes does.
A trivial solution would be to first remove all elements and then push the desired elements in the desired order. But since I know that most of the time the transforms will be quite small, equivalent to single pushes orremoves, I want to “reuse” any existing correct order in the list (for instance, transforming abcdef to abcde would require just one remove operation – quite a difference to the alternative (6+5 operations)). So, how to come up with the right (minimum) set of removes and list of pushes?
From what I can tell, you are going to be removing from anywhere and pushing to the back.
Because you can’t insert into the middle of the list, the only way you can minimize the number of operations is to go through the list linearly and remove any element that is not correct.
i.e. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 -> 2, 4, 6, 7, 8, 13, 14
(reached end)
If your push wasn’t so limited, there would be more efficient ways of doing this.