How do you do this? The values are unsorted but are of [1..n] Example array [3,1,2,5,7,8]. Answer: 4, 6
I saw this solution in
#include
using namespace std;
int main() {
int arr[]={3,1,2,5,7,8};
int n=6;
for(int i=0;i0 && arr[i]<=n){
int temp=arr[i]-1;
if(arr[i]!=arr[temp]){
swap(arr[i],arr[temp]);
i--;
}
}
}
for(int i=0;i
We can use the same array as a bucket. We traverse it once and keep on swapping the element to their correct index. If the value is less than 1 or more than array length, we leave it as it is. Initial Array- 3 1 2 5 7 8 swap(3,5) 5 1 2 3 7 8 swap(5,8) 8 1 2 3 7 5 After this we again traverse the array. The elements which are not in their proper position are missing hence we print the index. Time Complexity-O(n)