Minimum Swaps 2

  • + 0 comments

    I figure an index map can make it a whole a lot easier and straight forward:

    function minimumSwaps(arr) {
      const indexMap = {};
      arr.forEach((element, index) => {
        indexMap[element] = index;
      });
    
      let swap = 0;
      for (let i = 0; i < arr.length; i++) {
        //If the index doesn't match value, swap
        if (arr[i] !== i + 1) {
          const target = i + 1; //1
          const currTargetIndex = indexMap[target]; //index = 3
    
          //swap and keep track of the index map
          indexMap[target] = i;
          indexMap[arr[i]] = currTargetIndex;
    
          arr[currTargetIndex] = arr[i];
          arr[i] = target;
    
          swap += 1;
        }
      }
      return swap;
    }