Height Checker

easy array sorting

Problem

Students must stand in non-decreasing order of height. Given the current line in heights, return the number of indices where heights[i] differs from the sorted order (the "expected" line).

Inputheights = [1, 1, 4, 2, 1, 3]
Output3
expected = [1, 1, 1, 2, 3, 4]. Indices 2, 4, 5 differ.

def height_checker(heights):
    expected = sorted(heights)
    count = 0
    for i in range(len(heights)):
        if heights[i] != expected[i]:
            count += 1
    return count
function heightChecker(heights) {
  const expected = heights.slice().sort((a, b) => a - b);
  let count = 0;
  for (let i = 0; i < heights.length; i++) {
    if (heights[i] !== expected[i]) count++;
  }
  return count;
}
class Solution {
    public int heightChecker(int[] heights) {
        int[] expected = heights.clone();
        Arrays.sort(expected);
        int count = 0;
        for (int i = 0; i < heights.length; i++) {
            if (heights[i] != expected[i]) count++;
        }
        return count;
    }
}
int heightChecker(vector<int>& heights) {
    vector<int> expected = heights;
    sort(expected.begin(), expected.end());
    int count = 0;
    for (int i = 0; i < (int)heights.size(); i++) {
        if (heights[i] != expected[i]) count++;
    }
    return count;
}
Time: O(n log n) Space: O(n)