Height Checker Problem
Description
LeetCode Problem 1051.
A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the i^th student in line.
You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the i^th student in line (0-indexed).
Return the number of indices where heights[i] != expected[i].
Example 1:
Input: heights = [1,1,4,2,1,3]
Output: 3
Explanation:
heights: [1,1,4,2,1,3]
expected: [1,1,1,2,3,4]
Indices 2, 4, and 5 do not match.
Example 2:
Input: heights = [5,1,2,3,4]
Output: 5
Explanation:
heights: [5,1,2,3,4]
expected: [1,2,3,4,5]
All indices do not match.
Example 3:
Input: heights = [1,2,3,4,5]
Output: 0
Explanation:
heights: [1,2,3,4,5]
expected: [1,2,3,4,5]
All indices match.
Constraints:
1 <= heights.length <= 1001 <= heights[i] <= 100
Solution
Approach: Counting Sort
expected is just heights sorted, so the answer is the number of positions where heights differs from its sorted copy.
Sorting would work, but heights are between 1 and 100, so counting sort builds the expected order in linear time without storing it. Count how many students have each height. Then walk through the heights from 1 to 100: the next count[h] positions of expected all hold h, so compare each of them with heights at the same position and count the mismatches.
Complexity: O(n + M) time and O(M) space, where M = 100 is the largest height.
class Solution:
def heightChecker(self, heights: List[int]) -> int:
count = [0] * 101 # heights are 1..100, so a counting sort gives the expected order
for h in heights:
count[h] += 1
mismatches = 0
i = 0
for h in range(1, 101):
for _ in range(count[h]): # expected[i] is h for the next count[h] places
if heights[i] != h:
mismatches += 1
i += 1
return mismatches