# The Array Height Checker Problem in Java

## The challenge

Students are asked to stand in non-decreasing order of heights for an annual photo.

Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height.

Notice that when a group of students is selected they can reorder in any possible way between themselves and the non selected students remain on their seats.

Example 1:

```Input: heights = [1,1,4,2,1,3]
Output: 3
Explanation:
Current array : [1,1,4,2,1,3]
Target array  : [1,1,1,2,3,4]
On index 2 (0-based) we have 4 vs 1 so we have to move this student.
On index 4 (0-based) we have 1 vs 3 so we have to move this student.
On index 5 (0-based) we have 3 vs 4 so we have to move this student.
```

Example 2:

```Input: heights = [5,1,2,3,4]
Output: 5
```

Example 3:

```Input: heights = [1,2,3,4,5]
Output: 0
```

Constraints:

• `1 <= heights.length <= 100`
• `1 <= heights[i] <= 100`

## The solution

The easiest way to solve this is to sort a copy of the array, then compare which values are different.

```.wp-block-code{border:0;padding:0}.wp-block-code>div{overflow:auto}.shcb-language{border:0;clip:rect(1px,1px,1px,1px);-webkit-clip-path:inset(50%);clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal;word-break:normal}.hljs{box-sizing:border-box}.hljs.shcb-code-table{display:table;width:100%}.hljs.shcb-code-table>.shcb-loc{color:inherit;display:table-row;width:100%}.hljs.shcb-code-table .shcb-loc>span{display:table-cell}.wp-block-code code.hljs:not(.shcb-wrap-lines){white-space:pre}.wp-block-code code.hljs.shcb-wrap-lines{white-space:pre-wrap}.hljs.shcb-line-numbers{border-spacing:0;counter-reset:line}.hljs.shcb-line-numbers>.shcb-loc{counter-increment:line}.hljs.shcb-line-numbers .shcb-loc>span{padding-left:.75em}.hljs.shcb-line-numbers .shcb-loc::before{border-right:1px solid #ddd;content:counter(line);display:table-cell;padding:0 .75em;text-align:right;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;width:1%}```class Solution {
// our method
public int heightChecker(int[] heights) {
// clone the input array
int[] heights2 = Arrays.copyOf(heights, heights.length);

// sort the new array to compare against
Arrays.sort(heights2);

// keep a count to return
int count = 0;

// loop through the input array
for (int i=0; i<heights.length; i++) {
// if the sorted value doesn't match
// then increment
if (heights[i]!=heights2[i]) count++;
}

// return our count
return count;
}
}
```Code language: Java (java)```
Tags:
Subscribe
Notify of