HI WELCOME TO KANSIRIS

Check if array elements are consecutive

Leave a Comment

 Given an unsorted array of numbers, write a function that returns true if the array consists of consecutive numbers. 

Examples: 
a) If the array is {5, 2, 3, 1, 4}, then the function should return true because the array has consecutive numbers from 1 to 5.
b) If the array is {83, 78, 80, 81, 79, 82}, then the function should return true because the array has consecutive numbers from 78 to 83.
c) If the array is {34, 23, 52, 12, 3}, then the function should return false because the elements are not consecutive.
d) If the array is {7, 6, 5, 5, 3, 4}, then the function should return false because 5 and 5 are not consecutive.Method 1 (Use Sorting) 

1) Sort all the elements. 
2) Do a linear scan of the sorted array. If the difference between the current element and the next element is anything other than 1, then return false. If all differences are 1, then return true.

using System;
  
class GFG {
  
// Function to Check if array
// elements are consecutive
 
static bool areConsecutive(int []arr, int n)
{
    //Sort the array
    Array.Sort(arr);
    // checking the adjacent elements
    for(int i=1;i<n;i++)
    {
        if(arr[i]!=arr[i-1]+1)
        {
            return false;
        }
    }
    return true;
}
 
    /* Driver program to test above
    functions */
    public static void Main()
    {
        int []arr = {5, 4, 2, 3, 1, 6};
        int n = arr.Length;
          
        if (areConsecutive(arr, n) == true)
            Console.Write("Array elements "
                      + "are consecutive");
        else
            Console.Write("Array elements "
                  + "are not consecutive");
    }
}
  
// This code is contributed by Aarti_Rathi
Output
 Array elements are consecutive 

Time Complexity: O(n log n) 
Space Complexity: O(1) 

Method 2 (Use visited array) 
The idea is to check for the following two conditions. If the following two conditions are true, then return true. 
1) max – min + 1 = n where max is the maximum element in the array, min is the minimum element in the array and n is the number of elements in the array. 
2) All elements are distinct.
To check if all elements are distinct, we can create a visited[] array of size n. We can map the ith element of input array arr[] to the visited array by using arr[i] – min as the index in visited[]. 
 

using System;
 
class GFG {
     
    /* The function checks if the array elements
    are consecutive If elements are consecutive,
    then returns true, else returns    false */
    static bool areConsecutive(int []arr, int n)
    {
        if (n < 1)
            return false;
 
        /* 1) Get the minimum element in array */
        int min = getMin(arr, n);
 
        /* 2) Get the maximum element in array */
        int max = getMax(arr, n);
 
        /* 3) max - min + 1 is equal to n, then
        only check all elements */
        if (max - min + 1 == n)
        {
             
            /* Create a temp array to hold visited
            flag of all elements. Note that, calloc
            is used here so that all values are
            initialized as false */
            bool []visited = new bool[n];
            int i;
             
            for (i = 0; i < n; i++)
            {
                 
                /* If we see an element again, then
                return false */
                if (visited[arr[i] - min] != false)
                    return false;
 
                /* If visited first time, then mark
                the element as visited */
                visited[arr[i] - min] = true;
            }
             
            /* If all elements occur once, then
            return true */
            return true;
        }
        return false; // if (max - min + 1 != n)
    }
 
    /* UTILITY FUNCTIONS */
    static int getMin(int []arr, int n)
    {
        int min = arr[0];
         
        for (int i = 1; i < n; i++)
        {
            if (arr[i] < min)
                min = arr[i];
        }
         
        return min;
    }
 
    static int getMax(int []arr, int n)
    {
        int max = arr[0];
         
        for (int i = 1; i < n; i++)
        {
            if (arr[i] > max)
                max = arr[i];
        }
         
        return max;
    }
 
    /* Driver program to test above functions */
    public static void Main()
    {
        int []arr = {5, 4, 2, 3, 1, 6};
        int n = arr.Length;
         
        if (areConsecutive(arr, n) == true)
            Console.Write("Array elements are"
                              + " consecutive");
        else
            Console.Write("Array elements are"
                         + " not consecutive");
    }
}
 
// This code is contributed by nitin mittal.
Output
 Array elements are consecutive 

Time Complexity: O(n) 
Auxiliary Space: O(n) 

Method 3 (Mark visited array elements as negative) 
This method is O(n) time complexity and O(1) extra space, but it changes the original array, and it works only if all numbers are positive. We can get the original array by adding an extra step though. It is an extension of method 2, and it has the same two steps. 
1) max – min + 1 = n where max is the maximum element in the array, min is the minimum element in the array and n is the number of elements in the array. 
2) All elements are distinct.
In this method, the implementation of step 2 differs from method 2. Instead of creating a new array, we modify the input array arr[] to keep track of visited elements. The idea is to traverse the array and for each index i (where 0 ≤ i < n), make arr[arr[i] – min]] as a negative value. If we see a negative value again then there is repetition. 

using System;
 
class GFG {
     
    /* The function checks if the array
    elements are consecutive If elements
    are consecutive, then returns true,
    else returns false */
    static bool areConsecutive(int []arr, int n)
    {
        if (n < 1)
            return false;
 
        /* 1) Get the minimum element in
        array */
        int min = getMin(arr, n);
 
        /* 2) Get the maximum element in
        array */
        int max = getMax(arr, n);
 
        /* 3) max-min+1 is equal to n then
        only check all elements */
        if (max - min + 1 == n)
        {
            int i;
            for (i = 0; i < n; i++)
            {
                int j;
 
                if (arr[i] < 0)
                    j = -arr[i] - min;
                else
                    j = arr[i] - min;
 
                // if the value at index j
                // is negative then
                // there is repetition
                if (arr[j] > 0)
                    arr[j] = -arr[j];
                else
                    return false;
            }
 
            /* If we do not see a negative
            value then all elements
            are distinct */
            return true;
        }
 
        // if (max-min+1 != n)
        return false;
    }
 
    /* UTILITY FUNCTIONS */
    static int getMin(int []arr, int n)
    {
        int min = arr[0];
        for (int i = 1; i < n; i++)
        {
            if (arr[i] < min)
                min = arr[i];
        }
        return min;
    }
 
    static int getMax(int []arr, int n)
    {
        int max = arr[0];
        for (int i = 1; i < n; i++)
        {
            if (arr[i] > max)
                max = arr[i];
        }
        return max;
    }
 
    /* Driver program to test above
    functions */
    public static void Main()
    {
        int []arr = {5, 4, 2, 3, 1, 6};
        int n = arr.Length;
         
        if (areConsecutive(arr, n) == true)
            Console.Write("Array elements "
                      + "are consecutive");
        else
            Console.Write("Array elements "
                  + "are not consecutive");
    }
}
 
// This code is contributed by nitin mittal.
Output
 Array elements are consecutive 

Note that this method might not work for negative numbers. For example, it returns false for {2, 1, 0, -3, -1, -2}.
Time Complexity: O(n) 
Auxiliary Space: O(1) 

Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers)

Method 4 (Using XOR property)

This method is O(n) time complexity and O(1) extra space, does not changes the original array, and it works every time.

  1. As elements should be consecutive, let’s find minimum element or maximum element in array.
  2. Now if we take xor of two same elements it will result in zero (a^a = 0).
  3. Suppose array is {-2, 0, 1, -3, 4, 3, 2, -1}, now if we xor all array elements with minimum element and keep increasing minimum element, the resulting xor will become 0 only if elements are consecutive
     

using System;
using System.Linq;
 
class GFG {
  
// Function to Check if array
// elements are consecutive
 
static bool areConsecutive(int []arr, int n)
{
    int min_ele = arr.Min();
    int num = 0;
    for(int i=0; i<n; i++){
        num ^= min_ele^arr[i];
        min_ele += 1;
    }
    if(num == 0)
        return true;
    return false;
}
 
    /* Driver program to test above
    functions */
    public static void Main()
    {
        int []arr = {5, 4, 2, 3, 1, 6};
        int n = arr.Length;
          
        if (areConsecutive(arr, n) == true)
            Console.Write("Array elements "
                      + "are consecutive");
        else
            Console.Write("Array elements "
                  + "are not consecutive");
    }
}
  
// This code is contributed by Aarti_Rathi
Output
 Array elements are consecutive 

Time Complexity: O(n) 
Auxiliary Space: O(1) 
 

Please suggest if someone has a better solution which is more efficient in terms of space and time.

modal for ads blocked disable

Leave a Comment

<style>

 .modal {

            display: none;

            position: fixed;

            z-index: 1;

            left: 0;

            top: 0;

            width: 100%;

            height: 100%;

            overflow: auto;

            background-color: rgb(0, 0, 0);

            background-color: rgba(0, 0, 0, 0.4);

        }



        .modal-content {

            background-color: #fefefe;

            margin: 5% auto;

            padding: 60px 0px;

            border: 1px solid #888;

            width: 50%;

            text-align: center;

        }


        .modal-title {

            line-height: 28px;

           display:block;

           margin-bottom:40px;


            color: #2f5492;

            font-size: 26px;

        }


        .modal-p {

            font-size: 20px;

            margin-top:15px;

font-weight:600;

        }


        .modal-x {

            margin-top: 40px;

            text-transform: uppercase;

             color: #2f5492;

            letter-spacing: 0.14em;

            font-size: 16px;

      font-weight:600;

        }

</style>

<script>


function disableScrolling(){

    var x=window.scrollX;

    var y=window.scrollY;

    window.onscroll=function(){window.scrollTo(x, y);};

}


function adBlockDownload()

{

alert("Please disable your ad blocker for Kansiris.org and download.");

}


function adBlockFunction()

{

setTimeout(function() { 

document.getElementById('myModal').style.display = 'block';

ga('send', 'event', 'Blocker', 'click','Blocker');


},2000);


disableScrolling();


//document.getElementById('ab-message').style.display = 'block';


var b = document.getElementById('downloadScript'); 

b.setAttribute("href", "#block");

b.setAttribute("onclick", "adBlockDownload();");


}

</script>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" onerror="adBlockFunction();"></script>


<div class='modal' id='myModal'>


<div class='modal-content'>

<b class='modal-title'>Thanks for visiting Kansiris</b>

<p class='modal-p'>We notice you have an ad blocker on.</p>

<p class='modal-p'>Advertisements help us provide quality content.</p>

<p class='modal-x'>Please turn ad blocker off for Kansiris.org</p>

</div>

</div>