Open In App
Related Articles

Maximum consecutive numbers present in an array

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Find the length of maximum number of consecutive numbers jumbled up in an array.
Examples: 
 

Input : arr[] = {1, 94, 93, 1000, 5, 92, 78};
Output : 3
The largest set of consecutive elements is
92, 93, 94

Input : arr[] = {1, 5, 92, 4, 78, 6, 7};
Output : 4
The largest set of consecutive elements is
4, 5, 6, 7


 


The idea is to use hashing. We traverse through the array and for every element, we check if it is the starting element of its sequence. If yes then by incrementing its value we search the set and increment the length. By repeating this for all elements, we can find the lengths of all consecutive sets in array. Finally we return length of the largest set.
 

C++

// CPP program to find largest consecutive numbers
// present in arr[].
#include <bits/stdc++.h>
using namespace std;
 
int findLongestConseqSubseq(int arr[], int n)
{
    /* We insert all the array elements into
       unordered set. */
    unordered_set<int> S;
    for (int i = 0; i < n; i++)
        S.insert(arr[i]);
 
    // check each possible sequence from the start
    // then update optimal length
    int ans = 0;
    for (int i = 0; i < n; i++) {
 
        // if current element is the starting
        // element of a sequence
        if (S.find(arr[i] - 1) == S.end()) {
 
            // Then check for next elements in the
            // sequence
            int j = arr[i];
 
            // increment the value of array element
            // and repeat search in the set
            while (S.find(j) != S.end())
                j++;
 
            // Update  optimal length if this length
            // is more. To get the length as it is
            // incremented one by one
            ans = max(ans, j - arr[i]);
        }
    }
    return ans;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 94, 93, 1000, 5, 92, 78 };
    int n = sizeof(arr) / sizeof(int);
    cout << findLongestConseqSubseq(arr, n) << endl;
    return 0;
}

                    

Java

// Java program to find largest consecutive
// numbers present in arr[].
import java.util.*;
 
class GFG
{
     
static int findLongestConseqSubseq(int arr[], int n)
{
    /* We insert all the array elements into
    unordered set. */
    HashSet<Integer> S = new HashSet<Integer>();
    for (int i = 0; i < n; i++)
        S.add(arr[i]);
 
    // check each possible sequence from the start
    // then update optimal length
    int ans = 0;
    for (int i = 0; i < n; i++)
    {
 
        // if current element is the starting
        // element of a sequence
        if(S.contains(arr[i]))
        {
 
            // Then check for next elements in the
            // sequence
            int j = arr[i];
 
            // increment the value of array element
            // and repeat search in the set
            while (S.contains(j))
                j++;
 
            // Update optimal length if this length
            // is more. To get the length as it is
            // incremented one by one
            ans = Math.max(ans, j - arr[i]);
        }
    }
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = {1, 94, 93, 1000, 5, 92, 78};
    int n = arr.length;
        System.out.println(findLongestConseqSubseq(arr, n));
}
}
 
// This code contributed by Rajput-Ji

                    

Python3

# Python3 program to find largest consecutive
# numbers present in arr.
 
def findLongestConseqSubseq(arr, n):
    '''We insert all the array elements into unordered set.'''
 
    S = set();
    for i in range(n):
        S.add(arr[i]);
 
    # check each possible sequence from the start
    # then update optimal length
    ans = 0;
    for i in range(n):
         
        # if current element is the starting
        # element of a sequence
        if S.__contains__(arr[i]):
             
            # Then check for next elements in the
            # sequence
            j = arr[i];
             
            # increment the value of array element
            # and repeat search in the set
            while(S.__contains__(j)):
                j += 1;
 
            # Update optimal length if this length
            # is more. To get the length as it is
            # incremented one by one
            ans = max(ans, j - arr[i]);
    return ans;
 
# Driver code
if __name__ == '__main__':
    arr = [ 1, 94, 93, 1000, 5, 92, 78 ];
    n = len(arr);
    print(findLongestConseqSubseq(arr, n));
 
# This code is contributed by 29AjayKumar

                    

C#

// C# program to find largest consecutive
// numbers present in arr[].
using System;
using System.Collections.Generic; public
 
class GFG
{
     
static int findLongestConseqSubseq(int []arr, int n)
{
    /* We insert all the array elements into
    unordered set. */
    HashSet<int> S = new HashSet<int>();
    for (int i = 0; i < n; i++)
        S.Add(arr[i]);
 
    // check each possible sequence from the start
    // then update optimal length
    int ans = 0;
    for (int i = 0; i < n; i++)
    {
 
        // if current element is the starting
        // element of a sequence
        if(S.Contains(arr[i]))
        {
 
            // Then check for next elements in the
            // sequence
            int j = arr[i];
 
            // increment the value of array element
            // and repeat search in the set
            while (S.Contains(j))
                j++;
 
            // Update optimal length if this length
            // is more. To get the length as it is
            // incremented one by one
            ans = Math.Max(ans, j - arr[i]);
        }
    }
    return ans;
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = {1, 94, 93, 1000, 5, 92, 78};
    int n = arr.Length;
    Console.WriteLine(findLongestConseqSubseq(arr, n));
}
}
 
// This code has been contributed by 29AjayKumar

                    

Javascript

<script>
 
// JavaScript program to find largest consecutive numbers
// present in arr[].
 
 
function findLongestConseqSubseq(arr, n) {
    /* We insert all the array elements into
    unordered set. */
    let S = new Set();
    for (let i = 0; i < n; i++)
        S.add(arr[i]);
 
    // check each possible sequence from the start
    // then update optimal length
    let ans = 0;
    for (let i = 0; i < n; i++) {
 
        // if current element is the starting
        // element of a sequence
        if (!S.has(arr[i] - 1)) {
 
            // Then check for next elements in the
            // sequence
            let j = arr[i];
 
            // increment the value of array element
            // and repeat search in the set
            while (S.has(j))
                j++;
 
            // Update optimal length if this length
            // is more. To get the length as it is
            // incremented one by one
            ans = Math.max(ans, j - arr[i]);
        }
    }
    return ans;
}
 
// Driver code
 
let arr = [1, 94, 93, 1000, 5, 92, 78];
let n = arr.length;
document.write(findLongestConseqSubseq(arr, n) + "<br>");
 
</script>

                    

Output
3


Time complexity : O(n)
Space complexity: O(n)

Another approach: The idea is to sort the array. We will traverse through the array and check if the difference between the current element and the previous element is one or not. If the difference is one we will increment the count of the length of the current sequence. Otherwise, we will check if the count of the length of our current subsequence is greater than the length of our previously counted sequence. If it is, we will update our answer and then we will update the count to one to start counting the length of another sequence. By repeating this for all elements, we can find the lengths of all consecutive sequences in the array. Finally, we return the length of the largest sequence.

C++

// CPP program to find largest consecutive numbers present
// in arr.
#include <bits/stdc++.h>
using namespace std;
 
int findLongestConseqSubseq(int arr[], int n)
{
   
  // The longest sequence in an empty array is, of
    // course, 0, so we can simply return that.
    if (n == 0) {
        return 0;
    }
 
    // We will arrange array elements in ascending order
    // using sort function.
    sort(arr, arr + n);
 
    // check each possible sequence from the start then
    // update optimal length
    int ans = 1;
    int count = 1;
    for (int i = 1; i < n; i++)
    {
       
        // For handling duplicate elements
        if (arr[i] != arr[i - 1])
        {
           
            // if difference between current element and
            // previous element is 1 then we want to
            // update our current sequence count
            if (arr[i] - arr[i - 1] == 1) {
                count += 1;
            }
           
            // otherwise, we will update our count to
            // zero to check for other sequences. before
            // updating count value we have to check if
            // current sequence length is more than our
            // ans. if count > ans then we want to
            // update our ans.
            else {
                ans = max(ans, count);
                count = 1;
            }
        }
    }
   
    // To handle the case in which last element is
    // present in longest sequence.
    return max(ans, count);
}
 
// Driver code
int main()
{
    int arr[] = { 1, 94, 93, 1000, 5, 92, 78 };
    int n = sizeof(arr) / sizeof(int);
   
    // Function call
    cout << findLongestConseqSubseq(arr, n) << endl;
    return 0;
}
 
// This code is contributed by Naveen Shah.

                    

Java

// Java program to find largest consecutive numbers present
// in arr.
import java.io.*;
import java.util.*;
 
class GFG {
 
  static int findLongestConseqSubseq(int[] arr, int n)
  {
 
    // The longest sequence in an empty array is, of
    // course, 0, so we can simply return that.
    if (n == 0) {
      return 0;
    }
 
    // We will arrange array elements in ascending order
    // using sort function.
    Arrays.sort(arr);
 
    // check each possible sequence from the start then
    // update optimal length
    int ans = 1;
    int count = 1;
    for (int i = 1; i < n; i++) {
      // For handling duplicate elements
      if (arr[i] != arr[i - 1]) {
        // if difference between current element and
        // previous element is 1 then we want to
        // update our current sequence count
        if (arr[i] - arr[i - 1] == 1) {
          count += 1;
        }
        // otherwise, we will update our count to
        // zero to check for other sequences. before
        // updating count value we have to check if
        // current sequence length is more than our
        // ans. if count > ans then we want to
        // update our ans.
        else {
          ans = Math.max(ans, count);
          count = 1;
        }
      }
    }
 
    // To handle the case in which last element is
    // present in longest sequence.
    return Math.max(ans, count);
  }
 
  public static void main(String[] args)
  {
    int[] arr = { 1, 94, 93, 1000, 5, 92, 78 };
    int n = arr.length;
 
    // Function call
    System.out.print(findLongestConseqSubseq(arr, n));
  }
}
 
// This code is contributed by lokeshmvs21.

                    

Python3

# Python3 program to find largest consecutive
# numbers present in arr.
 
 
def findLongestConseqSubseq(arr, n):
    #The longest sequence in an empty array is, of course, 0, so we can simply return that.
    if n==0:
       return 0
       
    #We will arrange array elements in ascending order using sort function.
    arr.sort()
 
    # check each possible sequence from the start
    # then update optimal length
    ans = 1
    count = 1
    for i in range(1, n):
      #For handling duplicate elements
      if arr[i]!=arr[i-1]:
 
        # if difference between current element and previous element is 1
        # then we want to update our current sequence count
 
        if arr[i]-arr[i-1] == 1:
            count += 1
 
        # otherwise, we will update our count to zero to check for other sequences.
        # before updating count value we have to check if current sequence length is more than our ans.
        # if count > ans then we want to update our ans.
 
        else:
            ans = max(ans, count)
            count = 1
 
    return max(ans,count) #To handle the case in which last element is present in longest sequence.
 
 
# Driver code
if __name__ == '__main__':
    arr = [1, 94, 93, 1000, 5, 92, 78]
    n = len(arr)
    print(findLongestConseqSubseq(arr, n))
 
  
# This code is contributed by sanjanasikarwar24

                    

C#

// C# program to find largest consecutive numbers present
// in arr.
using System;
using System.Collections;
 
public class GFG {
 
  static int findLongestConseqSubseq(int[] arr, int n)
  {
 
    // The longest sequence in an empty array is, of
    // course, 0, so we can simply return that.
    if (n == 0) {
      return 0;
    }
 
    // We will arrange array elements in ascending order
    // using sort function.
    Array.Sort(arr);
 
    // check each possible sequence from the start then
    // update optimal length
    int ans = 1;
    int count = 1;
    for (int i = 1; i < n; i++) {
      // For handling duplicate elements
      if (arr[i] != arr[i - 1]) {
        // if difference between current element and
        // previous element is 1 then we want to
        // update our current sequence count
        if (arr[i] - arr[i - 1] == 1) {
          count += 1;
        }
        // otherwise, we will update our count to
        // zero to check for other sequences. before
        // updating count value we have to check if
        // current sequence length is more than our
        // ans. if count > ans then we want to
        // update our ans.
        else {
          ans = Math.Max(ans, count);
          count = 1;
        }
      }
    }
 
    // To handle the case in which last element is
    // present in longest sequence.
    return Math.Max(ans, count);
  }
 
  static public void Main()
  {
 
    // Code
    int[] arr = { 1, 94, 93, 1000, 5, 92, 78 };
    int n = arr.Length;
 
    // Function call
    Console.Write(findLongestConseqSubseq(arr, n));
  }
}
 
// This code is contributed by lokeshmvs21.

                    

Javascript

function findLongestConseqSubseq(arr, n) {
  // The longest sequence in an empty array is, of course, 0, so we can simply return that.
  if (n == 0) return 0;
 
  // We will arrange array elements in ascending order using sort function.
  arr.sort((a, b) => a - b);
 
  // check each possible sequence from the start
  // then update optimal length
  let ans = 1,
    count = 1;
  for (let i = 1; i < n; i++) {
    // For handling duplicate elements
    if (arr[i] != arr[i - 1]) {
      // if difference between current element and previous element is 1
      // then we want to update our current sequence count
      if (arr[i] - arr[i - 1] == 1) {
        count++;
      }
      // otherwise, we will update our count to zero to check for other sequences.
      // before updating count value we have to check if current sequence length is more than our ans.
      // if count > ans then we want to update our ans.
      else {
        ans = Math.max(ans, count);
        count = 1;
      }
    }
  }
 
  // To handle the case in which last element is present in longest sequence.
  return Math.max(ans, count);
}
 
// Driver code
let arr = [1, 94, 93, 1000, 5, 92, 78];
let n = arr.length;
console.log(findLongestConseqSubseq(arr, n));
//This code is contributed by sanjanasikarwar24

                    

Output
3

Time complexity : O(nlogn)

Space complexity: O(1)

Another approach: The idea is to use set. We traverse through the array and for every element, we check if it is the starting element of its sequence( no element whose value is less than the current element by one is present in the set ). If yes then by incrementing its value we search for other valid elements that could be present in the set and increment the length of the sequence accordingly. By repeating this for all elements, we can find the lengths of all consecutive sequences in the array. Finally, we return the length of the largest sequence

C++

#include <iostream>
#include <set>
using namespace std;
 
int findLongestConseqSubseq(int arr[], int n)
{
    // We insert all the array elements into set.
    set<int> S;
    for (int i = 0; i < n; i++)
        S.insert(arr[i]);
 
    // check each possible sequence from the start
    // then update optimal length
    int ans = 0;
    for (int i = 0; i < n; i++)
    {
       
        // if current element is the starting
        // element of a sequence
        if (S.find(arr[i] - 1) == S.end())
        {
           
            // Then check for next elements in the
            // sequence
            int j = arr[i];
            while (S.find(j) != S.end())
                j++;
 
            // update optimal length if this length
            // is more
            ans = max(ans, j - arr[i]);
        }
    }
    return ans;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 94, 93, 1000, 5, 92, 78 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findLongestConseqSubseq(arr, n) << endl;
    return 0;
}
// This code is contributed by sanjanasikarwar24

                    

Java

import java.util.HashSet;
import java.util.Set;
 
public class Main {
  public static int findLongestConseqSubseq(int[] arr, int n)
  {
 
    // We insert all the array elements into set.
    Set<Integer> S = new HashSet<>();
    for (int i = 0; i < n; i++)
      S.add(arr[i]);
 
    // check each possible sequence from the start
    // then update optimal length
    int ans = 0;
    for (int i = 0; i < n; i++)
    {
 
      // if current element is the starting
      // element of a sequence
      if (!S.contains(arr[i] - 1))
      {
 
        // Then check for next elements in the
        // sequence
        int j = arr[i];
        while (S.contains(j))
          j++;
 
        // update optimal length if this length
        // is more
        ans = Math.max(ans, j - arr[i]);
      }
    }
    return ans;
  }
 
  // Driver code
  public static void main(String[] args) {
    int[] arr = { 1, 94, 93, 1000, 5, 92, 78 };
    int n = arr.length;
    System.out.println(findLongestConseqSubseq(arr, n));
  }
}
 
// This code is contributed by sanjanasikarwar24

                    

Python3

# Python3 program to find largest consecutive
# numbers present in arr.
def findLongestConseqSubseq(arr, n):
    '''We insert all the array elements into set.'''
 
    S = set(arr)
 
    # check each possible sequence from the start
    # then update optimal length
    ans = 0
    for e in arr:
 
        # i contains current element of array
        i = e
        # count represents the length of current sequence
        count = 1
 
        # if current element is the starting
        # element of a sequence
        if i-1 not in S:
            # Then check for next elements in the
            # sequence
            while i+1 in S:
                # increment the value of array element
                # and repeat search in the set
                i += 1
                count += 1
 
            # Update optimal length if this length
            # is more.
            ans = max(ans, count)
    return ans
 
 
# Driver code
if __name__ == '__main__':
    arr = [1, 94, 93, 1000, 5, 92, 78]
    n = len(arr)
    print(findLongestConseqSubseq(arr, n))
 
# This code is contributed by sanjanasikarwar24

                    

C#

using System;
using System.Collections.Generic;
 
public class MainClass {
  public static int findLongestConseqSubseq(int[] arr, int n) {
    // We insert all the array elements into set.
    HashSet<int> S = new HashSet<int>();
    foreach (int x in arr)
      S.Add(x);
 
    // check each possible sequence from the start
    // then update optimal length
    int ans = 0;
    foreach (int x in arr) {
      // if current element is the starting
      // element of a sequence
      if (!S.Contains(x - 1)) {
        // Then check for next elements in the
        // sequence
        int j = x;
        while (S.Contains(j)) j++;
 
        // update optimal length if this length
        // is more
        ans = Math.Max(ans, j - x);
      }
    }
    return ans;
  }
 
  // Driver code
  public static void Main() {
    int[] arr = { 1, 94, 93, 1000, 5, 92, 78 };
    int n = arr.Length;
    Console.WriteLine(findLongestConseqSubseq(arr, n));
  }
}
//This code is contributed by sanjanasikarwar24

                    

Javascript

function findLongestConseqSubseq(arr, n)
{
 
  // We insert all the array elements into set.
  let S = new Set(arr);
 
  // check each possible sequence from the start
  // then update optimal length
  let ans = 0;
  for (let i = 0; i < n; i++)
  {
   
    // if current element is the starting
    // element of a sequence
    if (!S.has(arr[i] - 1))
    {
     
      // Then check for next elements in the
      // sequence
      let j = arr[i];
      while (S.has(j)) j++;
 
      // update optimal length if this length
      // is more
      ans = Math.max(ans, j - arr[i]);
    }
  }
  return ans;
}
 
// Driver code
let arr = [1, 94, 93, 1000, 5, 92, 78];
let n = arr.length;
console.log(findLongestConseqSubseq(arr, n));
 
// This code is contributed by sanjanasikarwar24

                    

Output
3

Time complexity: O(nlogn)

Space complexity: O(n)



Last Updated : 12 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads