Students are standing in a line at a height check. The heights are recorded in an array. To check if students are in non-decreasing order by height, sort the array and compare. Count the number of positions where the heights differ from the sorted order.
Create a sorted copy of the heights array using the built-in sort function. Iterate through both arrays simultaneously, counting indices where the values differ. This count represents the minimum number of students that need to move to achieve sorted order.
Time is O(n log n) for sorting plus O(n) for the comparison pass. Space is O(n) for the sorted copy. Edge cases include an empty array (return 0), a single student (return 0), and an already sorted array (return 0).
The height checker problem is commonly used to assess understanding of sorting and array comparison operations. It demonstrates how sorting creates a reference ordering against which the original arrangement can be measured.
An alternative approach uses counting sort since heights are in a limited range (1 to 100 in the problem constraints), achieving O(n + k) time where k is the range of heights.
The counting sort alternative achieves O(n + k) time where k is the height range (1-100), demonstrating how problem constraints can enable more efficient solutions than general-purpose sorting.Example Input & Output
Already sorted.
Differences at indices 2,4,5.
All out of order.
Empty.
Single.
Algorithm Flow

Solution Approach
Sort a copy. Count differences between original and sorted.
Time O(n log n), Space O(n).
Best Answers
import java.util.*;
class Solution {
public int solution(int[] heights) {
int[] s=heights.clone();
Arrays.sort(s);
int c=0;
for (int i=0;i<heights.length;i++) if (heights[i]!=s[i]) c++;
return c;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
