A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. You are given an integer array heights
representing the heights of the students in the order they are currently standing. Return the number of indices where the heights do not match the order when sorted.
Input: heights = [1,1,4,2,1,3]
Output: 3
Explanation:
heights: [1, 1, 4, 2, 1, 3]
expected: [1, 1, 1, 2, 3, 4]
Indices 2, 4, and 5 do not match.
The solution involves comparing the given array with a sorted version of the same array and counting the number of discrepancies between the two lists.
def heightChecker(heights):
expected = sorted(heights)
mismatch_count = 0
for i in range(len(heights)):
if heights[i] != expected[i]:
mismatch_count += 1
return mismatch_count
Overall time complexity: O(n log n) due to the sorting step, which is the most time-consuming operation.
Let’s take the example provided: heights = [1,1,4,2,1,3]
Thus, the function returns 3.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?