Height Checker — LeetCode 1051 Python Solution
EasyArrayCounting SortSorting
- Problem
- #1051
- Pattern
- Sorting
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- heights = [1,1,4,2,1,3]
- Output
- 3
- Explanation
- heights: [1,1,4,2,1,3]
Python solution
Python
class Solution:
def heightChecker(self, heights: List[int]) -> int:
expected = sorted(heights)
return sum(a != b for a, b in zip(heights, expected))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Sorting
Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1051. Height Checker is filed here because LeetCode tags it Sorting and Counting Sort, which is the vocabulary this hub collects.
The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1051. Height Checker?
- LeetCode 1051. Height Checker is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1051. Height Checker?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 1051. Height Checker?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1051. Height Checker cover?
- LeetCode 1051. Height Checker is tagged Array, Counting Sort and Sorting on LeetCode.