
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Example
Let us see the following implementation to get better understanding −
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
Advertisements