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: School Photo Line-UpCurrent:114213Expected:1112343 students are in wrong positions
Understanding the Visualization
1
Current Line
Students standing in current order
2
Expected Line
How students should be arranged by height
3
Count Misplaced
Number of students in wrong positions
Key Takeaway
🎯 Key Insight: Compare current arrangement with sorted arrangement to find how many students are out of place
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