Maximum consecutive numbers present in an array
Last Updated :
12 Jul, 2023
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>
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
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
Time complexity: O(nlogn)
Space complexity: O(n)
Similar Reads
Collect maximum points in an array with k moves
Given an array of integer and two values k and i where k is the number of moves and i is the index in the array. The task is to collect maximum points in the array by moving either in single or both directions from given index i and making k moves. Note that every array element visited is considered
9 min read
Maximum count of equal numbers in an array after performing given operations
Given an array of integers. The task is to find the maximum count of equal numbers in an array after applying the given operation any number of times. In an operation: Choose two elements of the array a[i], a[j] (such that i is not equals to j) and, Increase number a[i] by 1 and decrease number a[j]
5 min read
Maximum XOR of Two Numbers in an Array | Set 2
Given an array arr[] consisting of N integers, the task is to find the maximum Bitwise XOR from all the possible pairs in the given array. Examples: Input: arr[] = {25, 10, 2, 8, 5, 3}Output: 28Explanation:The maximum result is 5^25 = 28. Input: arr[] = {1, 2, 3, 4, 5, 6, 7}Output: 7Explanation:The
12 min read
Maximum even numbers present in any subarray of size K
Given an array arr[] of size N and an integer K, the task is to find the maximum number of even numbers present in any subarray of size K. Examples: Input: arr[] = {2, 3, 5, 4, 7, 6}, K = 3 Output: 2 Explanation: Subarrays of size K(=3) with maximum count of even numbers are { arr[3], arr[4], arr[5]
12 min read
Largest perfect cube number in an Array
Given an array of N integers. The task is to find the largest number which is a perfect cube. Print -1 if there is no number that is perfect cube. Examples: Input : arr[] = {16, 8, 25, 2, 3, 10} Output : 25 Explanation: 25 is the largest number that is a perfect cube. Input : arr[] = {36, 64, 10, 16
7 min read
Maximise the size of consecutive element subsets in an array
Given an integer array and an integer k. The array elements denote positions of points on a 1-D number line, find the maximum size of the subset of points that can have consecutive values of points which can be formed by placing another k points on the number line. Note that all coordinates should b
12 min read
Find a number that divides maximum array elements
Given an array A[] of N non-negative integers. Find an Integer greater than 1, such that maximum array elements are divisible by it. In case of same answer print the smaller one.Examples: Input : A[] = { 2, 4, 5, 10, 8, 15, 16 }; Output : 2 Explanation: 2 divides [ 2, 4, 10, 8, 16] no other element
13 min read
Find all numbers that divide maximum array elements
Given an array of N numbers, the task is to print all the numbers greater than 1 which divides the maximum of array elements. Examples: Input: a[] = {6, 6, 12, 18, 13} Output: 2 3 6 All the numbers divide the maximum of array elements i.e., 4 Input: a[] = {12, 15, 27, 20, 40} Output: 2 3 4 5 Approac
7 min read
Maximize array elements upto given number
Given an array of integers, a number and a maximum value, task is to compute the maximum value that can be obtained from the array elements. Every value on the array traversing from the beginning can be either added to or subtracted from the result obtained from previous index such that at any point
15+ min read
Find the count of maximum contiguous Even numbers
Given an array arr[] of N elements. The task is to find the maximum number of the contiguous even numbers in the given array. Examples: Input: arr[] = {1, 2, 3, 4, 6, 7} Output: 2 Maximum contiguous even number sequence is {4, 6} Input: arr[] = {1, 0, 2, 4, 3, 8, 9} Output: 3 Maximum contiguous even
8 min read