1051. Height Checker

Photo by Ben Wicks on Unsplash

1051. Height Checker

class Solution:
    def heightChecker(self, heights: List[int]) -> int:
        minVal = float('inf')
        maxVal = 0
        freq = defaultdict(int)

        for height in heights:
            freq[height] += 1
            minVal = min(minVal, height)
            maxVal = max(maxVal, height)

        sortedArr = []
        for val in range(minVal, maxVal + 1):
            while freq.get(val, 0) > 0:                
                sortedArr.append(val)
                freq[val] -= 1

        count = 0
        for index, height in enumerate(heights):
            if height != sortedArr[index]:
                count += 1

        return count