Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function solve(arr) {
- let sorted = arr.slice().sort((a, b) => a - b);
- let swapsAsc = findSwaps(arr, sorted);
- let swapsDesc = findSwaps(arr, sorted.slice().reverse());
- return Math.min(swapsAsc, swapsDesc);
- }
- function findSwaps(arr, sorted) {
- // map value to index
- let value2index = arr.reduce((acc, curr, index) => {acc[curr] = index; return acc}, {});
- let answer = 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 a[i]
- let temp = arr[i];
- arr[i] = arr[position];
- arr[position] = temp;
- // Update the position of a[position] in the value2index map
- value2index[arr[position]] = position;
- // Increment swap count
- answer++;
- }
- }
- return answer;
- }
- console.log(solve([2, 5, 3, 1])); // should return 2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement