Nilimsankar's blog

By Nilimsankar, history, 4 months ago, In English

Given two arrays, current and desired, each representing the order of n elements, find the minimum number of operations required to transform current into desired.

Operation: - In one operation, you can select an element from the end of the current array and insert it at any position within the array.

Output: - Return the minimum number of such operations needed to make current equal to desired.

TC-1 current — 2 1 3 5 4 desired — 2 4 1 5 3 output = 2

TC-2 current — 2 1 3 desired — 1 2 3 output= 2

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
4 months ago, # |
  Vote: I like it +3 Vote: I do not like it

The answer is the N — the length of the longest prefix that is in the correct order (more specifically the longest prefix of current such that for all i,j, such that i is before j in the prefix, i is before j in the desired array)

Imagine the target is 1 2 3 4 5 and we have 2 1 3 4 5. The answer is 4 because we have to move all but the 2. We must swap the 2 and the 1 but in order to move the one we have to move everything to the right of it. So if a prefix array is in relatively the correct order we don't have to move any of its elements, but we have to move the rest of them.