Height Checker

I really liked the solution to this problem as the code is extremely short. Thanks to Kotlin’s built-in operators.

class Solution {
    fun heightChecker(heights: IntArray): Int {
        return heights
            .sorted()
            .mapIndexed { index, i -> if(heights[index] != i) 1 else 0 }
            .sum()
    }
}

First, we sort the heights into ascending order then compare each item with the old values and check which of them flipped. Return 1 or 0 accordingly. Finally, the mapIndexed operator will give us a series of 1’s and 0’s and all that is left to do is to compute their sum.

Runtime: 176 ms, faster than 37.14% of Kotlin online submissions for Height Checker.
Memory Usage: 35.9 MB, less than 100.00% of Kotlin online submissions for Height Checker.