• + 0 comments

    My Kotlin solution

    fun minimumBribes(q: Array<Int>): Unit {
        var result = 0
        var list = q.toMutableList()
        for (index in (q.lastIndex) downTo 0){
            val sortedValue = (index +1)
            if (list[index] == sortedValue){
                // make the list smaller so that next iteration would take less time to find the lastIndexOf
                list.removeAt(index)
                continue
            }
            
            // search from tail of list gets the index quicker in this case
            val unSortedIndex = list.lastIndexOf(sortedValue)
            val shift = (index - unSortedIndex)
            if(shift > 2){
                println("Too chaotic")
                return
            }
            
            list.removeAt(unSortedIndex) 
            result += shift
        }
        println(result)    
    }