Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function solve(arr) {
- let sorted = [...arr].sort((a, b) => a - b);
- let swapsAsc = findSwaps([...arr], sorted);
- let swapsDesc = findSwaps([...arr], sorted.reverse());
- return Math.min(swapsAsc, swapsDesc);
- }
- function findSwaps(arr, sorted) {
- // map value to index
- let value2index = {};
- arr.forEach((val, i) => value2index[val] = i);
- let swaps = 0;
- for (let i = 0; i < arr.length; i++) {
- // At index i there must be value sorted[i]
- if (arr[i] != sorted[i]) {
- // Find the position of value sorted[i] in the input array
- let position = value2index[sorted[i]];
- // Swap sorted[i] with arr[i]
- [arr[i], arr[position]] = [arr[position], arr[i]];
- // Update the position of arr[position] in the value2index map
- value2index[arr[position]] = position;
- // Increment swap count
- swaps++;
- }
- }
- return swaps;
- }
- console.log(solve([2, 5, 3, 1])); // should return 2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement