Related Articles

# Length of longest consecutive sequence that can be formed from Array by converting 0s

• Last Updated : 17 Sep, 2021

Given an array arr of N integers, the task is to calculate the length of longest sequence of consecutive integers that can be formed from the array. It is also given that 0’s in the array can be converted to any value.

Example:

Input: N = 7, A = {0, 6, 5, 10, 3, 0, 11}
Output: 5
Explanation: The maximum consecutive sequence formed can be {3, 4, 5, 6, 7}. As 4, 7 are not present in the array, we can change 2 zeroes to 4 and 7.

Input: N = 6, A = {0, 0, 1, 2, 6, 0}
Output: 6
Explanation: The maximum consecutive sequence formed can be {1, 2, 3, 4, 5, 6}

Approach: Given problem can be solved with the help of binary search and prefix sum array:

• Calculate total zeroes in the array and store them in a variable count which indicates the total possible changes that can be made
• Repeating and zero values in the given array are removed so that array contains only unique non-zero values
• Create an auxiliary array and initialize those indices value to 1, whose values are present in the given array
• Auxiliary array is turned into prefix sum array
• Iterate the prefix array and at every iteration perform binary search with lower limit as current index and upper limit as last index of the array
• Let current index be l and the rightmost possible index as r. For each mid = (l + r) / 2, Check if this range[l, mid] is achievable with total allowed changes
• Update l = mid +1 if the above statement is true otherwise r = mid – 1
• Calculate maximum length for all starting values

Below is the implementation of the above approach:

## C++

 `// C++ implementation for the above approach` `#include ``using` `namespace` `std;` `// Function to calculate maximum``// possible consecutive numbers``// with changes allowed``int` `maximumConsecutiveNumbers(``int` `arr[], ``int` `N)``{``    ``// Store all non-zero elements``    ``// in a new vector and``    ``// calculate total zero elements``    ``vector<``int``> v;` `    ``// Variable to store the``    ``// count of zero elements``    ``int` `count = 0;` `    ``for` `(``int` `i = 0; i < N; i++) {``        ``if` `(arr[i] == 0) {``            ``count++;``        ``}``        ``else` `{``            ``v.push_back(arr[i]);``        ``}``    ``}` `    ``// Sort the array``    ``sort(v.begin(), v.end());` `    ``// Remove all the duplicates``    ``// from the array``    ``(v).erase(unique(v.begin(),``                     ``v.end()),``              ``(v).end());` `    ``// Variable to store the maximum``    ``// value of the sequence``    ``int` `MAXN = 1100000;` `    ``// Make the prefix array``    ``vector<``int``> pref(MAXN + 1, 0);` `    ``for` `(``int` `i = 0; i < v.size(); i++) {``        ``pref[v[i]]++;``    ``}` `    ``for` `(``int` `i = 1; i <= MAXN; i++) {``        ``pref[i] += pref[i - 1];``    ``}` `    ``int` `mx = 0;` `    ``// Iterate for each element and``    ``// use binary search``    ``for` `(``int` `i = 1; i <= MAXN; i++) {` `        ``int` `l = i, r = MAXN;``        ``int` `local_max = 0;``        ``while` `(l <= r) {``            ``int` `mid = (l + r) / 2;` `            ``// Conversions equal to number``            ``// of zeros, can be made upto mid``            ``if` `(pref[mid] - pref[i - 1]``                    ``+ count``                ``>= (mid - i + 1)) {` `                ``l = mid + 1;``                ``local_max = max(local_max,``                                ``mid - i + 1);``            ``}` `            ``else` `{``                ``r = mid - 1;``            ``}``        ``}``        ``mx = max(mx, local_max);``    ``}``    ``return` `mx;``}` `// Driver Code``int` `main()``{``    ``int` `N = 7;``    ``int` `arr[] = { 0, 6, 5, 10, 3, 0, 11 };``    ``cout << maximumConsecutiveNumbers(arr, N);``}`

## C#

 `// C# implementation for the above approach``using` `System;``using` `System.Collections.Generic;``using` `System.Linq;` `class` `GFG``{``  ` `    ``// Function to calculate maximum``    ``// possible consecutive numbers``    ``// with changes allowed``    ``static` `int` `maximumConsecutiveNumbers(``int``[] arr, ``int` `N)``    ``{``        ``// Store all non-zero elements``        ``// in a new vector and``        ``// calculate total zero elements``        ``List<``int``> v = ``new` `List<``int``>();` `        ``// Variable to store the``        ``// count of zero elements``        ``int` `count = 0;` `        ``for` `(``int` `i = 0; i < N; i++) {``            ``if` `(arr[i] == 0) {``                ``count++;``            ``}``            ``else` `{``                ``v.Add(arr[i]);``            ``}``        ``}` `        ``// Sort the array``        ``v.Sort();` `        ``// Remove all the duplicates``        ``// from the array``        ``List<``int``> distinct = v.Distinct().ToList();` `        ``// Variable to store the maximum``        ``// value of the sequence``        ``int` `MAXN = 1100000;` `        ``// Make the prefix array``        ``List<``int``> pref = ``new` `List<``int``>(``new` `int``[MAXN + 1]);` `        ``for` `(``int` `i = 0; i < distinct.Count; i++) {``            ``pref[distinct[i]]++;``        ``}` `        ``for` `(``int` `i = 1; i <= MAXN; i++) {``            ``pref[i] += pref[i - 1];``        ``}` `        ``int` `mx = 0;` `        ``// Iterate for each element and``        ``// use binary search``        ``for` `(``int` `i = 1; i <= MAXN; i++) {` `            ``int` `l = i, r = MAXN;``            ``int` `local_max = 0;``            ``while` `(l <= r) {``                ``int` `mid = (l + r) / 2;` `                ``// Conversions equal to number``                ``// of zeros, can be made upto mid``                ``if` `(pref[mid] - pref[i - 1] + count``                    ``>= (mid - i + 1)) {` `                    ``l = mid + 1;``                    ``local_max``                        ``= Math.Max(local_max, mid - i + 1);``                ``}` `                ``else` `{``                    ``r = mid - 1;``                ``}``            ``}``            ``mx = Math.Max(mx, local_max);``        ``}``        ``return` `mx;``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main()``    ``{``        ``int` `N = 7;``        ``int``[] arr = { 0, 6, 5, 10, 3, 0, 11 };``        ``Console.Write(maximumConsecutiveNumbers(arr, N));``    ``}``}` `// This code is contributed by ukasp.`

## Javascript

 ``
Output
`5`

Time Complexity: O(N*log(K)), where K is maximum value in the array
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up