Height Checker in Python

Suppose a set of students have to be arranged in non-decreasing order of their heights for a photograph. If we have an array of students, we have to return the minimum number of students that are not present in correct position. So if the array is like [1, 1, 4, 2, 1, 3], then output will be 3. So students with height 4, 3 and the last 1 are not standing in the correct position.

To solve this, we will follow these steps −

  • answer := 0
  • let x := Array in sorted form
  • ley y := Array
  • for i := 0 to size of Array – 1 −
    • if x[i] is not same as y[i], then increase answer by 1
  • return answer


Let us see the following implementation to get better understanding −

 Live Demo

class Solution(object):
   def heightChecker(self, heights):
      ans = 0
      x = sorted(heights)
      y = heights
      for i in range(len(x)):
         if x[i]!=y[i]:
      return ans
ob1 = Solution()