Skip to content

Instantly share code, notes, and snippets.

@OmarKRostom
Created September 3, 2019 01:54
Show Gist options
  • Save OmarKRostom/478fdeb006c0d4876c668ee7095d4031 to your computer and use it in GitHub Desktop.
Save OmarKRostom/478fdeb006c0d4876c668ee7095d4031 to your computer and use it in GitHub Desktop.
Solution to minimum swaps 2 on hackerrank
// Complete the minimumSwaps function below.
fun minimumSwaps(arr: Array<Int>): Int {
var numberOfSwaps = 0
val sortingMap: HashMap<Int, Int> = HashMap()
// Build hashing map, ex.
// [7, 1, 3, 2, 4, 5, 6]
// [0, 1, 2, 3, 4, 5, 6]
for (hashingIndex in 0 until arr.size) {
sortingMap[arr[hashingIndex]] = hashingIndex
}
for (loopingIndex in 0 until arr.size) {
if (loopingIndex + 1 != arr[loopingIndex]) {
val temp = arr[loopingIndex]
arr[loopingIndex] = loopingIndex + 1
arr[sortingMap[loopingIndex + 1]!!] = temp
sortingMap[temp] = sortingMap[loopingIndex + 1]!!
sortingMap[loopingIndex + 1] = loopingIndex
numberOfSwaps++
}
}
return numberOfSwaps
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment