# 1051. Height Checker

## Sort

T: O(nlogn)

S: O(n)

```java
class Solution {
    public int heightChecker(int[] heights) {
        int[] sortedHeights = heights.clone();
        Arrays.sort(sortedHeights);
        int count = 0;
        for (int i = 0; i < heights.length; i++) {
            if (sortedHeights[i] != heights[i]) {
                count++;
            }
        }
        return count;
    }
}
```

### Bucket sort

T: O(max), see if max is too large or not

S: O(max)

```java
class Solution {
    public int heightChecker(int[] heights) {
        int max = 0;
        for (int h : heights) {
            max = Math.max(max, h);
        }
        int[] bucket = new int[max+1];
        for (int h : heights) {
            bucket[h]++;
        }

        int result = 0;
        int bucketIdx = 0;
        for (int h : heights) {
            while (bucket[bucketIdx] == 0) {
                bucketIdx++;
            }
            if (bucketIdx != h) { // bucketIdx is the actual height
                result++;
            }
            bucket[bucketIdx]--;
        }
        return result;
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/sort/1051.-height-checker.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
