Sponsored
Sponsored
This approach involves creating an 'expected' array by sorting the given 'heights' array. Once sorted, you compare each element of the original 'heights' array with the corresponding element in the 'expected' array. Count the number of mismatches, which will be your answer.
Time Complexity: O(n log n) due to sorting. Space Complexity: O(n) to store the 'expected' array.
1def heightChecker(heights):
2 expected = sorted(heights)
3 count = 0
4 for i in range(len(heights)):
5 if heights[i] != expected[i]:
6 count += 1
7 return count
8
9heights = [1, 1, 4, 2, 1, 3]
10print(heightChecker(heights))
In Python, sort 'heights' to get 'expected'. Loop over both lists to count mismatches where values differ.
Given the constraint that heights range between 1 and 100, we can use a counting sort based approach to find deviations from the expected array without explicitly sorting.
Time Complexity: O(n + k) where k is 100 (a constant, heights range). Space Complexity: O(k) for the count array.
1#include <iostream>
2using namespace std;
int heightChecker(int* heights, int heightsSize) {
int countHeights[101] = {0};
for (int i = 0; i < heightsSize; ++i) {
countHeights[heights[i]]++;
}
int count = 0, currHeight = 0;
for (int i = 0; i < heightsSize; ++i) {
while (countHeights[currHeight] == 0) {
currHeight++;
}
if (heights[i] != currHeight) {
count++;
}
countHeights[currHeight]--;
}
return count;
}
int main() {
int heights[] = {1, 1, 4, 2, 1, 3};
int result = heightChecker(heights, sizeof(heights) / sizeof(heights[0]));
cout << result << endl;
return 0;
}
In C++, similar to C, maintain 'countHeights' to frequency count heights. Use it to infer order for direct mismatch checking.