Minimum Swaps 2

  • + 0 comments

    Kotlin solution

    fun minimumSwaps(arr: Array<Int>): Int {
        val list = arr.toMutableList()
        var swapCount = 0
        for (i in arr.lastIndex downTo 0){
            val value = list[i]
            val sortedValue = (i + 1)
            if(value == sortedValue){
                list.removeLast()
                continue
            }
            
            val swapTargetIndex = list.indexOf(sortedValue)
            list[swapTargetIndex] = value
            list.removeLast()
            swapCount++
        }
        return swapCount
    }