Please refer this link for the problem statement click here
Javascript program for lily's homework hacker rank solution
function swap(a, i, j) {
let temp = a[i];
a[i] = a[j];
a[j] = temp;
}
function lilysHomework(a) {
let noOfSwaps = 0, indexes = {};
let sortedArray = a.slice().sort((a, b) => a - b);
for (let i = 0; i < a.length; i++) {
indexes[a[i]] = i;
}
for (let i = 0; i < a.length; i++) {
if (sortedArray[i] != a[i]) {
noOfSwaps++;
let index = indexes[sortedArray[i]];
indexes[a[i]] = index;
swap(a, index, i);
}
}
return noOfSwaps;
}
Time Complexity : O(n)
Space Complexity : O(n)
0 Comments