Problem · Array
Count Students Outside Their Sorted Positions
Learn this problemProblem statement
You are given an array heights, where heights[i] is the height of the student currently standing at index i.
The students should stand in nondecreasing height order. Return the number of indices whose current height differs from the height that would appear at that index after sorting the entire array.
Function
countStudentsOutOfPosition(heights: int[]) → intExamples
Example 1
heights = [1,1,4,2,1,3]return = 3The sorted array is [1,1,1,2,3,4]. Indices 2, 4, and 5 differ.
Example 2
heights = [5,1,2,3,4]return = 5After sorting, every index contains a different height.
Example 3
heights = [1,2,2,4]return = 0The students are already in nondecreasing order.
Constraints
1 <= heights.length <= 1000001 <= heights[i] <= 1000000000