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: 3Explanation:
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: 5Explanation:
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: 0Explanation:
heights: [1,2,3,4,5]
expected: [1,2,3,4,5]
All indices match.
Constraints:
1 <= heights.length <= 1001 <= heights[i] <= 100Before attempting this problem, you should be comfortable with:
The problem asks us to count how many students are standing in the wrong position compared to where they should be if arranged by height.
If we sort the array, we get the "expected" order.
By comparing each position in the original array with the sorted version, we can count mismatches.
res to 0.Since heights are constrained to a small range (1 to 100), we can use counting sort for a more efficient solution.
Instead of sorting the entire array, we count how many times each height appears.
Then we reconstruct the expected sorted order by iterating through possible heights and adding each one according to its count.
Finally, we compare the original array with this expected array.
101 (to cover heights 1 through 100).1 to 100 and appending each height according to its count.class Solution:
def heightChecker(self, heights: List[int]) -> int:
count = [0] * 101
for h in heights:
count[h] += 1
expected = []
for h in range(1, 101):
c = count[h]
for _ in range(c):
expected.append(h)
res = 0
for i in range(len(heights)):
if heights[i] != expected[i]:
res += 1
return resWhere is the size of the input array, and is the range of numbers.
When sorting the array to get the expected order, some developers accidentally sort the original array in place. This destroys the original order, making it impossible to compare positions. Always create a copy of the array before sorting, or use a method that returns a new sorted array without modifying the original.
In languages like JavaScript, the default sort() method sorts elements as strings, not numbers. This means [1, 10, 2] would be sorted as [1, 10, 2] instead of [1, 2, 10]. Always provide a numeric comparator function (e.g., (a, b) => a - b) to ensure correct sorting behavior.
Sign in to join the discussion