We are given an array of int which are not sorted (Do not assume that the array contain only positive integer and no duplicate elements.). Each time, we are only allowed to pick a random element and put it at the end of the array. What is the minimum steps required to make this array a sorted list (in ascending order)?
A illustrating example for you to understand
Suppose the given list is {2, 1, 4, 3}, then the minimum step required is 3.
step 1: pick 2, put it at the end of the array, now the array is {1, 4, 3, 2}
step 2: pick 3, put it at the end of the array, now the array is {1, 4, 2, 3}
step 3: pick 4, put it at the end of the array, now the array is {1, 2, 3, 4}
I have tried to solve this problem on my own. But I am not sure if my solution has minimum time complexity and space complexity.
My solutions
suppose the given array is nums
, which is a vector of int. My solution is (now with complete code to run it on your own)
#include <vector>
#include <iostream>
using namespace std;
int main(){
int N; // N is the number of elements in this array
cin >> N;
vector<int> nums(N);
vector<int> nums_copy(N);
for (int i = 0; i != N; ++i){
cin >> nums[i];
nums_copy[i] = nums[i];
}
sort(nums_copy.begin(), nums_copy.end());
size_t j = 0;
for (size_t i = 0, end = nums.size(); i != end; ++i){
if (nums[i] == nums_copy[j])
++j;
}
cout << nums.size() - j << endl;
return 0;
}
The idea is to sort the original array, and then count the number of element in the original array which are in correct order in the sorted array(j
in the above code). So the minimum steps required is just nums.size()-j
.
The space complexity is O(n)
and time complexity is O(nlog(n))
which is just
the time complexity of sorting the array.
If you think that my solution is wrong or you have a better solution in term of either time or space complexity or both, share your solution.