Situation
To begin with, you have an array/list A, then you want to transform it to an expected array/list B given. The only actions that you can apply on array are InsertAt
and DeleteAt
where they are able to insert and delete an element at certain index from list.
note: Array B is always sorted while Array A may not be.
For instance, you have an array A of [1, 4, 3, 6, 7]
and you want it to become [2, 3, 4, 5, 6, 6, 7, 8]
One way of doing that is let A undergo following actions:
deleteAt(0); // which will delete element 1, arrayA now [4, 3, 6, 7]
deleteAt(0); // delete element 4 which now at index 0
// array A now [3, 6, 7]
insertAt(0, 2); // Insert value to at index 0 of array A
// array A now [2, 3, 6, 7]
insertAt(2, 4); // array now [2, 3, 4, 6, 7]
insertAt(3, 5); // array Now [2, 3, 4, 5, 6, 7]
insertAt(5, 6); // array Now [2, 3, 4, 5, 6, 6, 7]
insertAt(7, 8); // array Now [2, 3, 4, 5, 6, 6, 7, 8]
On the above example, 7 operations were done on array A to transform it to array we wanted.
Hence, how do we find the what are the steps to transform A to B, as well as the minimum steps? Thanks!
btw, solution of deleting all element at A then add everything from B to A is only applicable when A & B have nothing in common.
My thoughts
What I have done so far:
- Compare the array A and array B, then save delete all the elements in Array A that can't be found in array B.
- Find the longest increasing subsequence from the common list of A and B.
- delete All elements that are not in Longest increasing sub sequence.
- compare what is left with B, then add elements accordingly.
However, I'm struggling from implementing that..
Change log
- fixed a typo of missing out element
7
, now least operation is 7. - Added
MY THOUGHTS
section - There was a answer that elaborated on Levenshtein distance (AKA min edit distance), somehow it disappeared.. But I found that really useful after reading git/git levenshtein.c file, it seems to be a faster algorithm then what I already have. However, I'm not sure will that algorithm give me the detailed steps, or it is only capable of giving min num of steps.