Height Checker (LeetCode 1051): Solution and Explanation

Easy
Array
Sorting
Counting Sort

Students stand in a line. Count how many positions hold a different height than the same position in the line sorted by height.

Intuition

The question is not how many swaps are needed, only how many students stand in a spot the sorted line gives to a different height. So build the sorted line and compare it to the real one position by position.

Sorting a copy works and is short. But heights are limited to 1..100, which is exactly the setting where counting sort shines.

Once each height is counted, the sorted line is simply: all the 1s, then all the 2s, and so on. You never need to store it, because you can read it off the buckets while walking the real line.

Keep a pointer cur on the smallest non-empty bucket. At each position, cur is the height the sorted line wants there. Compare, then take one from that bucket.

Approach: Counting sort compared on the fly

  1. Make count with 101 zeros and add 1 to count[h] for every height.
  2. Set mismatches = 0 and cur = 1.
  3. For each height h in line order, advance cur while count[cur] == 0.
  4. If h != cur, increase mismatches. Then decrease count[cur].
  5. Return mismatches.

Step-by-step example

heights = [1,1,4,2,1,3]
  1. Count: three 1s, one 2, one 3, one 4.
  2. Positions 0 and 1: the sorted line wants 1 and the students are 1, so both match.
  3. Position 2: the sorted line still wants 1 (one left), but a 4 stands there. Mismatch 1.
  4. Position 3: the 1s are used up, so cur moves to 2. The student is 2, a match.
  5. Position 4: cur moves to 3 but the student is 1. Mismatch 2.
  6. Position 5: cur moves to 4 but the student is 3. Mismatch 3. Return 3.

Code: Python, Java, C++

1class Solution:
2    def heightChecker(self, heights: List[int]) -> int:
3        count = [0] * 101
4        for h in heights:
5            count[h] += 1
6        mismatches, cur = 0, 1
7        for h in heights:
8            while count[cur] == 0:
9                cur += 1
10            if h != cur:
11                mismatches += 1
12            count[cur] -= 1
13        return mismatches
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + 100)

Counting is one pass, and the walk moves cur across at most 100 buckets in total while visiting each student once.

Space

O(100)

Only the fixed-size count array is stored, independent of n.

Other approaches

Sort a copy and compare (time O(n log n), space O(n))

Copy heights, sort the copy, and count the indices where the two arrays differ. Simplest to write and plenty fast for n <= 100.

Common mistakes

  • Sorting heights in place and then comparing it with itself. Sort a copy, or the answer is always 0.
  • Counting swaps or moves instead of mismatched positions. The problem only asks how many positions differ.
  • Forgetting to skip empty buckets before comparing, which compares against a height nobody has.

Frequently asked questions

Why does counting sort work here?

Heights are integers between 1 and 100. With a fixed small range, counting each value and reading the counts in order produces the sorted sequence in linear time.

Is the answer the minimum number of students to move?

It is a count of out-of-place positions. Each of those students must move, and moving just those students into their sorted spots is enough, so the two numbers agree.

Can the answer ever be 1?

No. If exactly one position differed, that student's height would be missing from the rest of the line, which cannot happen because both lines hold the same heights. Mismatches come in groups of at least two.