Search code examples
arraysalgorithmsortinglanguage-agnostic

Find the number of remove-then-append operations needed to sort a given array


This is an interview question. A swap means removing any element from the array and appending it to the back of the same array. Given an array of integers, find the minimum number of swaps needed to sort the array.

Is there a solution better than O(n^2)?

For example:

Input array: [3124].

The number of swaps: 2 ([3124] -> [1243] -> [1234]).


Solution

  • This might work in O(nlogn) even if we don't assume array of consecutive values.
    If we do - it can be done in O(n). One way of doing it is with O(n) space and O(nlogn) time.
    Given array A sort it (O(nlogn)) into a second array B.
    now... (arrays are indexed from 1)

    swaps = 0
    b = 1
    for a = 1 to len(A)
      if A[a] == B[b]
        b = b + 1
      else
        swaps = swaps + 1