Similar Problems

Similar Problems not available

Height Checker - Leetcode Solution

Companies:

LeetCode:  Height Checker Leetcode Solution

Difficulty: Easy

Topics: sorting array  

The Height Checker problem on LeetCode is as follows:

Students are asked to stand in non-decreasing order of heights for an annual photo.

Return the minimum number of students not standing in the right positions. (This is the number of students that must move in order for all students to be standing in non-decreasing order of height.)

Example 1:

Input: heights = [1,1,4,2,1,3] Output: 3 Explanation: Students with heights 4, 3 and the last 1 are not standing in the right positions.

The solution to this problem involves comparing the original order of the heights list with a sorted list of the same heights. If there are any differences between these two lists, we can assume that those students did not stand in the right position.

Therefore, we can create a new list by sorting the original heights list. Then, we can iterate through the two lists simultaneously and count the number of times the heights are different.

Here is the detailed code solution in Python:

class Solution:
    def heightChecker(self, heights: List[int]) -> int:
        sorted_heights = sorted(heights)
        count = 0
        for i in range(len(heights)):
            if heights[i] != sorted_heights[i]:
                count += 1
        return count

In this solution, we first sort the original heights list and store it in a new variable called sorted_heights. Then, we set the count variable to zero, which will keep track of the number of students that did not stand in the right position.

Next, we loop through the original heights list using the range() function and compare each height to its corresponding height in the sorted_heights list. If the heights are different, we know that the student did not stand in the right position, so we increment the count variable.

Finally, we return the count variable, which represents the minimum number of students that did not stand in the right position.

Height Checker Solution Code

1