You are viewing a single comment's thread. Return to all comments →
Here's a shorter version, same logic but using a Map.
function minimumSwaps(arr) { const arr2 = arr.slice().sort((a, b) => a - b); const indexes = new Map(); arr.forEach((v, i) => indexes.set(v, i)); let swaps = 0; arr.forEach((v, i) => { if (v !== arr2[i]) { swaps++; arr[indexes.get(arr2[i])] = v; arr[i] = arr2[i]; indexes.set(v, indexes.get(arr2[i])); } }); return swaps; }
Seems like cookies are disabled on this browser, please enable them to open this website
Minimum Swaps 2
You are viewing a single comment's thread. Return to all comments →
Here's a shorter version, same logic but using a Map.