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.
1function
In JavaScript, array 'countHeights' is used to count occurrences of each height, simulating sorting for mismatch counting directly.