The problem “1051. Height Checker” from LeetCode asks us to determine the number of students that are not standing in the correct positions according to their height. We are given a list of integers where each integer represents the height of a student, and the students are standing in a line. The goal is to count how many students need to be moved to make the array sorted in non-decreasing order.
#include <vector>
#include <algorithm>
int heightChecker(std::vector<int>& heights) {
// Create a sorted copy of the heights array
std::vector<int> sortedHeights = heights;
std::sort(sortedHeights.begin(), sortedHeights.end());
// Count the number of differing positions
int count = 0;
for (size_t i = 0; i < heights.size(); ++i) {
if (heights[i] != sortedHeights[i]) {
++count;
}
}
return count;
}
Thus, the overall time complexity of the function is (O(n \log n)), which is efficient given the constraints.
Input:
std::vector<int> heights = {1, 1, 4, 2, 1, 3};
Execution:
{1, 1, 1, 2, 3, 4}
{1, 1, 4, 2, 1, 3}
Output:
int result = heightChecker(heights); // result should be 4
This approach efficiently counts the number of mismatches to determine how many students are out of order.
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?