Height Checker | Array Problem | LeetCode 1051

4 years ago Lalit Bhagtani 0

Problem Statement

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

Write a program to find out the minimum number of students that are not standing in the right positions. This is the number of students that must move in order for all students to be standing in a non-decreasing order of height.

Example 

Height Checker

Input :- [1, 1, 4, 2, 1, 3]
Output :- 3
Input :- [1, 5, 4, 2, 6, 3]
Output :- 5

Solution

This problem can be solved in following steps :-

  1. Create a copy of the given input array heights.
  2. Sort the given input array heights in increasing order.
  3. Compare each element of both the arrays heights and its copy, If elements is not equal then increase the count by 1.
  4. Return the value of count as a result.

Program

import java.util.Arrays;

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		int result = main.heightChecker(new int[] {1, 5, 4, 2, 6, 3});
		System.out.println(result);
	}
	
	/* Solution */    
	public int heightChecker(int[] heights) {
        int[] newHeights = new int[heights.length];
        for(int i=0; i<heights.length; i++){
            newHeights[i] = heights[i];
        }
        
        Arrays.sort(heights);
        
        int count = 0;
        for(int i=0; i<heights.length; i++){
            if(newHeights[i] != heights[i]){
                count++;
            }
        }
        return count;
    }
}

Result

5

Similar Post

  1. Day of the Week
  2. Move Zeroes to End of Array
  3. Find Pivot Index in Array

That’s all for Height Checker in Java, If you liked it, please share your thoughts in a comments section and share it with others too.