#1051
Height Checker
EasyArraySortingCounting SortCounting SortArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of sorting the array, we can count the occurrences of each height and then determine how many heights are out of place based on their expected positions. This is more efficient.
⚙️
Algorithm
3 steps- 1Step 1: Create a count array of size 101 (since heights range from 1 to 100) to count occurrences of each height.
- 2Step 2: Populate the count array by iterating through the heights array.
- 3Step 3: Initialize a counter and iterate through the count array to determine the expected heights and compare with the original heights, counting mismatches.
solution.py13 lines
1def heightChecker(heights):
2 count = [0] * 101
3 for h in heights:
4 count[h] += 1
5 mismatches = 0
6 index = 0
7 for height in range(1, 101):
8 while count[height] > 0:
9 if heights[index] != height:
10 mismatches += 1
11 index += 1
12 count[height] -= 1
13 return mismatchesℹ
Complexity note: The counting step runs in O(n) time, and since the count array size is constant (101), the space complexity is O(1).
- 1Sorting helps us find the expected order quickly.
- 2Counting occurrences can help us avoid sorting and improve efficiency.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.