We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • HackerRank Home

    HackerRank

  • |
  • Prepare
  • Certify
  • Compete
  • Hiring developers?
  1. Minimum Swaps 2
  2. Discussions

Minimum Swaps 2

Problem
Submissions
Leaderboard
Discussions
Editorial

    You are viewing a single comment's thread. Return to all comments →

  • IbadAhmad
    4 months ago+ 0 comments

    My solution in javascript

    function minimumSwaps(arr) {
        let sortedArray = arr
        let numberPositions = {}
        let numberOfSwaps = 0
        
        arr.forEach((n,i)=>{
            numberPositions[n] = i
        })
        
        arr.forEach((_,i)=>{
            if (sortedArray[i] != i+1){
                let temp = sortedArray[i]
                sortedArray[i] = sortedArray[numberPositions[i+1]]
                sortedArray[numberPositions[i+1]] = temp
                numberPositions[temp] = numberPositions[i+1]
                numberPositions[i+1] = i
                numberOfSwaps+=1
            }
        })
    
        return numberOfSwaps
    }
    
    -1|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy