Maximum consecutive numbers present in an array - GeeksforGeeks

22 Mar, 2022
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++
Java
Python3
C#
Javascript
// 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 codeint main(){    int arr[] = { 1, 94, 93, 1000, 5, 92, 78 };    int n = sizeof(arr) / sizeof(int);    cout << findLongestConseqSubseq(arr, n) << endl;    return 0;}
// 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 codepublic 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 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 codeif __name__ == '__main__':    arr = [ 1, 94, 93, 1000, 5, 92, 78 ];    n = len(arr);    print(findLongestConseqSubseq(arr, n)); # This code is contributed by 29AjayKumar
// 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 codepublic 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
<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>
3

Time complexity : O(n2)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.
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 codeif __name__ == '__main__':    arr = [1, 94, 93, 1000, 5, 92, 78]    n = len(arr)    print(findLongestConseqSubseq(arr, n))   # This code is contributed by sanjanasikarwar24
3

Time complexity : O(nlogn)
Space complexity: O(1)
Another approach: 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( 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
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 codeif __name__ == '__main__':    arr = [1, 94, 93, 1000, 5, 92, 78]    n = len(arr)    print(findLongestConseqSubseq(arr, n)) # This code is contributed by sanjanasikarwar24
3

Time complexity: O(n)
Space complexity: O(n)
Rajput-Ji
29AjayKumar
gfgking
UserHandle0
sanjanasikarwar24
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum
Hashing | Set 2 (Separate Chaining)