You are given an almost sorted array [ could either be in ascending/descending order but that info is not given ]. There is only one misplaced item in the sorted array which if found and put in proper place would make the array sorted. provide an efficient implementation to solve this problem and indicate average case time and space complexity required to solve this.
Ex:- { 1, 2, 4, 5, 6, 7, 3, 8, 9, 10 } The answer is index = 6 and item 3 must be placed at index 2 to make the array sorted.
Ex:- { 4, 1, 2, 3 } Answer is index=0 and item 4 must be placed at index=4 to make the array sorted.
Same logic applies to descending order as well.
Ex:- { 4, 3, 2, 5 } Item 5 must be placed at index = 0 to make this array sorted in descending order.
Edge Case Ex:- { 1 5 2 } This can be done either by placing 2 at index=1 [ ascending order sort ] or by placing 1 at index 2 [ descending order sort ] In such ambiguity make sure array is sorted ascending order. the i.e answer should be placed item 2 at index 1.
I have solved this problem in O(n) iteration [ only identifying the index ] and space complexity of O(1). Later I sort the array accordingly using sort from algorithm header.
Although I am sure that the solution can be done in O(n) my code does not look very elegant. I also found one case where it still does not work. Could not locate similar this problem on stack overflow being asked anywhere, hence asking.
any better/elegant simple solution? specifically the function :
pair getMisPlacedItemIndex(const vector& arr, const size_t& size)
My code is at https://rextester.com/PMYOCP84040
Aucun commentaire:
Enregistrer un commentaire