A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line.
You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed).
Return the number of indices whereheights[i] != expected[i].
Look at the constraints, we have just 100 elements at max in array. So, we can use bucketsort, with only 100 buckets to sort the array. This will reduce our sorting time complexity to O(n).
Now, one way can be we create a new sorted array based on this, and do the comparisons as in method 1.
But, what we can also do is - we use 2 pointers on heights and buckets - say i and j.
We find the non-zero height in the bucket. If it is not equal to ith height. If they don’t match, then we found one non matching height, and increment i, and reduce the count in buckets.
i =1 (heights[1] =1), j (r still expecting 1)
While bucket[j] isnot zero, so continue. j is1, which matches heights[1], ans remains 0. Decrement bucket[j] -> bucket[1] =1
i =2 (heights[2] =4), j (still expecting 1)
While bucket[j] isnot zero, so continue. j is1, which does notmatch heights[2], increment ans to 1. Decrement bucket[j] -> bucket[1] =0
i =3 (heights[3] =2), j (expecting 2 now because bucket[1] is zero)
While bucket[j] is zero, increment j to 2. j is2, which matches heights[3], ans remains 1. Decrement bucket[j] -> bucket[2] =0
i =4 (heights[4] =1), j (expecting 3 now because bucket[2] is zero)
While bucket[j] is zero, increment j to 3. j is3, which does notmatch heights[4], increment ans to 2. Decrement bucket[j] -> bucket[3] =0
i =5 (heights[5] =3), j (expecting 4 now because bucket[3] is zero)
While bucket[j] is zero, increment j to 4. j is4, which does notmatch heights[5] (which is3), increment ans to 3. Decrement bucket[j] -> bucket[4] =0