A school is trying to take an annual photo of all the students. The students are asked to stand in a single line in non-decreasing order by height. Let’s assume that heights are represented by an integer array. You need to return the number of indices where the heights do not match the expected heights.
public class HeightChecker {
public int heightChecker(int[] heights) {
// Create a copy of the original array
int[] expected = heights.clone();
// Sort the copied array
Arrays.sort(expected);
int mismatchCount = 0;
// Compare the original array to the sorted array
for (int i = 0; i < heights.length; i++) {
if (heights[i] != expected[i]) {
mismatchCount++;
}
}
return mismatchCount;
}
public static void main(String[] args) {
HeightChecker hc = new HeightChecker();
int[] heights = {1,1,4,2,1,3};
System.out.println(hc.heightChecker(heights)); // Output: 3
}
}
O(n)
, where n
is the number of students.O(n log n)
.O(n)
.Thus, the overall time complexity is dominated by the sorting step, which is O(n log n)
.
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?