Friday, 22 May 2020

check Array elements are consecutive


public class CheckArrayIsConsecutive {

  static boolean checkConsecutive(int[] arr){

        int min = Integer.MAX_VALUE;
        for(int i=0;i<arr.length;i++){
            if(min>arr[i]){
                min = arr[i];
            }
        }

        for(int i=0;i<arr.length;i++){
            if(Math.abs(arr[i])-min>=arr.length){ //means array size small than required consecutive element
                return false;
            }
            if(arr[Math.abs(arr[i])-min]<0){ //if we want to store negative at index there already a negative value
                return false;
            }

            arr[Math.abs(arr[i])-min] = -   arr[Math.abs(arr[i])-min];

        }


        return true;
    }
    public static void main(String[] args) {
        int[] arr = {77,78,76,75,72,73,74};
        boolean bool = checkConsecutive(arr);
        System.out.println(bool);
    }
}


output: true


if input below then output false:
 int[] arr = {77,78,76,75,72,73,79};

ref: https://github.com/mission-peace/interview/blob/master/src/com/interview/array/CheckIfArrayElementsAreConsecutive.java

No comments:

Post a Comment

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...