Height Checker in Python

PythonServer Side ProgrammingProgramming

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

Example

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]:
            ans+=1
      return ans
ob1 = Solution()
print(ob1.heightChecker([1,2,4,2,1,3]))

Input

[1,1,4,2,1,3]

Output

4
raja
Published on 16-Jan-2020 16:48:33
Advertisements