Problem Description
Given an array of student heights, determine how many positions do not match the expected order when the heights are sorted in non-decreasing order. Essentially, count the mismatches between the current ordering and the sorted (expected) ordering.
Key Insights
- Create a copy of the original heights array and sort it to form the expected order.
- Compare each element of the original array with the sorted array.
- Count the indices where the two arrays differ.
- The problem focuses on counting mismatches without needing to physically rearrange the array.
Space and Time Complexity
Time Complexity: O(n log n) due to the sorting step.
Space Complexity: O(n) for storing the sorted copy of the array.
Solution
The approach is to first sort a copy of the given array to know the correct order of heights. Then, iterate through both arrays simultaneously and count the positions where the elements differ. This gives the number of students that are not in their correct positions. The primary data structures used are arrays, and the algorithm leverages sorting followed by a simple linear scan.
Code Solutions
Below are solutions in Python, JavaScript, C++, and Java with detailed line-by-line comments.