Sort a copy of the heights and count index-wise differences from the original arrangement.
Complexity
O(n log n) time and O(n) space.
Count positions whose heights differ from the nondecreasing expected order.
Sort a copy of the heights and count index-wise differences from the original arrangement.
O(n log n) time and O(n) space.
package main
import "sort"
func heightChecker(heights []int) int {
expected := append([]int(nil), heights...)
sort.Ints(expected)
mismatches := 0
for index, height := range heights {
if height != expected[index] {
mismatches++
}
}
return mismatches
}
class Solution:
def heightChecker(self, heights: list[int]) -> int:
return sum(actual != expected for actual, expected in zip(heights, sorted(heights)))
function heightChecker(heights: number[]): number {
const expected = [...heights].sort((left, right) => left - right);
return heights.reduce((count, height, index) => count + Number(height !== expected[index]), 0);
}