Height Checker - Problem

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 ith 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 ith student in line (0-indexed).

Return the number of indices where heights[i] != expected[i].

Input & Output

Example 1 — Basic Case
$ Input: heights = [1,1,4,2,1,3]
Output: 3
💡 Note: Expected order is [1,1,1,2,3,4]. Positions 2, 3, and 5 have wrong heights (4≠1, 2≠2, 3≠4), so 3 students need to move.
Example 2 — Already Sorted
$ Input: heights = [5,1,2,3,4]
Output: 5
💡 Note: Expected order is [1,2,3,4,5]. All positions except none match, so all 5 students are in wrong positions.
Example 3 — Perfect Order
$ Input: heights = [1,2,3,4,5]
Output: 0
💡 Note: Already in non-decreasing order. No students need to move.

Constraints

  • 1 ≤ heights.length ≤ 100
  • 1 ≤ heights[i] ≤ 100

Visualization

Tap to expand
Height Checker - Optimal Solution INPUT Current Order (heights array) 1 1 4 2 1 3 heights = [1,1,4,2,1,3] 1 1 4 2 1 3 Index: 0 1 2 3 4 5 ALGORITHM STEPS 1 Sort heights array Create expected order 2 expected = [1,1,1,2,3,4] Sorted in non-decreasing 3 Compare element by element Count mismatches idx h[i] e[i] Match? 0 1 1 OK 1 1 1 OK 2 4 1 X 3 2 2 OK 4 1 3 X 5 3 4 X 4 Return mismatch count Indices 2, 4, 5 differ FINAL RESULT Mismatched Positions Highlighted heights: 1 1 4 2 1 3 expected: 1 1 1 2 3 4 idx: 0 1 2 3 4 5 Mismatches at indices: 2, 4, 5 OUTPUT 3 3 students need to move Key Insight: The optimal solution sorts the array to get the expected order, then counts differences. Time: O(n log n) for sorting. Space: O(n) for the expected array. Can also use counting sort for O(n). TutorialsPoint - Height Checker | Optimal Solution (Sort and Compare)
Asked in
Amazon 25 Google 20 Apple 15
78.0K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen