Height Checker

Let’s understand the problem first: We need to arrange students in non-decreasing order of their heights, and then compare the current order of heights with the expected order. The task is to count how many heights are out of place.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def heightChecker(self, heights: List[int]) -> int:
        # Create a sorted copy of the heights array
        expected = sorted(heights)

        # Initialize a variable to keep track of the number of mismatched heights
        mismatch_count = 0

        # Iterate through the original heights array
        for i in range(len(heights)):
            # Compare the original height with the expected height at the same index
            if heights[i] != expected[i]:
                # If they don't match, increment the mismatch_count by 1
                mismatch_count += 1

        # Return the total number of mismatched heights
        return mismatch_count

Explanation

  • We sort the given heights array to create the expected order of heights.
  • We then initialize a variable mismatch_count to keep track of the number of heights that are out of place.
  • We iterate through the heights array and compare each height with the corresponding height in the sorted expected array. If they don’t match, we increment the mismatch_count.
  • Finally, we return the total number of mismatched heights, which gives the number of indices where heights[i] is not equal to expected[i].