An algorithm that checks if the values of an array form one or two numerical sequences starting from 1

If the values of the array can form one or two numerical sequences then return 1 otherwise return 0.

For example the array [2,1,2,3] should return 1 when the array [4,1,3] should return 0.

Assume that:

  • N is an integer within the range [1..100,000];
  • each element of array A is an integer within the range [1..1,000,000,000].
import java.util.*;

class Algo {
    public boolean isEmptyArray(int[] Arr ){
        if ( Arr == null || Arr.length == 0) {
            return true;
        }
        return false;
    }
    public int algo(int[] A) {
        if (isEmptyArray(A)) return 0;
        Arrays.sort(A);
        if (A[0] != 1) return 0;
        int value = A.length;
        int lastValue = A[A.length -1];
        if ( value == lastValue ) {
            for(int i=0 ; i < A.length -1; i++ ){
                if (!(A[i+1] == i+1 || A[i+1] == i+2)) {
                    return 0;
                }
            }
            return 1;
        }
        return 0;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s