#1051

Height Checker

Easy Counting sort

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Students stand in a line. Count how many positions differ from where they'd be if the line were sorted by height (heights are 1..100).

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: how many students stand in the wrong place compared with the sorted line?

Why this works: heights are only 1..100, so counting sort gives the expected order in O(n).

Example: [1, 1, 4, 2, 1, 3] → expected [1, 1, 1, 2, 3, 4]

differences at indexes 2, 4, 5 → 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Sorting the original array in place and then comparing it with itself.

Solve on LeetCode ↗
Complexity
  • Time: O(n + 100).
  • Space: O(100).
Topic: Sorting
🎬 Episodes 24–28: video coming soon