Longest Subarray with an Extra 1
Last Updated :
11 Dec, 2024
Given a binary array arr[], the task is to find the length of the longest subarray having count of 1s exactly one more than count of 0s.
Examples:
Input: arr[] = [0, 1, 1, 0, 0, 1]
Output: 5
Explanation: The subarray from index 1 to 5, that is [1, 1, 0, 0, 1] has exactly one more 1s than 0s.
Input: arr[] = [0, 0, 0, 0]
Output: 0
Explanation: Since there are no 1s, there is no subarray having exactly one more 1s than 0s.
Input: arr[] = [1, 1, 1, 1]
Output: 1
Explanation: Since there are no 0s, all subarrays of size 1 have exactly one more 1s than 0s.
[Naive Approach] Iterating over all subarrays - O(n^2) Time and O(1) Space
The idea is to consider all possible subarrays while keeping a count of the number of 0s and 1s. The result will be the length of the longest subarray having count of 1s exactly one more than count of 0s.
C++
// C++ Code to find the length of longest subarray
// having count of 1's one more than count of 0's
// by iterating over all subarrays
#include <iostream>
#include <vector>
using namespace std;
int findLength(vector<int> &arr) {
int n = arr.size();
int res = 0;
for(int i = 0; i < n; i++) {
// Keep track of count of 0s and 1s
int cnt0 = 0, cnt1 = 0;
for(int j = i; j < n; j++) {
if(arr[j] == 1)
cnt1++;
else
cnt0++;
// Update res if we found a larger subarray with
// count of 1s one greater than count of 0s
if(cnt1 - cnt0 == 1) {
res = max(res, j - i + 1);
}
}
}
return res;
}
int main() {
vector<int> arr = { 0, 1, 1, 0, 0, 1 };
cout << findLength(arr);
return 0;
}
C
// C Code to find the length of longest subarray
// having count of 1's one more than count of 0's
// by iterating over all subarrays
#include <stdio.h>
int findLength(int arr[], int n) {
int res = 0;
for(int i = 0; i < n; i++) {
// Keep track of count of 0s and 1s
int cnt0 = 0, cnt1 = 0;
for(int j = i; j < n; j++) {
if(arr[j] == 1)
cnt1++;
else
cnt0++;
// Update res if we found a larger subarray with
// count of 1s one greater than count of 0s
if(cnt1 - cnt0 == 1) {
if (j - i + 1 > res) {
res = j - i + 1;
}
}
}
}
return res;
}
int main() {
int arr[] = { 0, 1, 1, 0, 0, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d", findLength(arr, n));
return 0;
}
Java
// Java Code to find the length of longest subarray
// having count of 1's one more than count of 0's
// by iterating over all subarrays
import java.util.*;
class GfG {
static int findLength(int[] arr) {
int n = arr.length;
int res = 0;
for (int i = 0; i < n; i++) {
// Keep track of count of 0s and 1s
int cnt0 = 0, cnt1 = 0;
for (int j = i; j < n; j++) {
if (arr[j] == 1)
cnt1++;
else
cnt0++;
// Update res if we found a larger subarray with
// count of 1s one greater than count of 0s
if (cnt1 - cnt0 == 1) {
res = Math.max(res, j - i + 1);
}
}
}
return res;
}
public static void main(String[] args) {
int[] arr = { 0, 1, 1, 0, 0, 1 };
System.out.println(findLength(arr));
}
}
Python
# Python Code to find the length of longest subarray
# having count of 1's one more than count of 0's
# by iterating over all subarrays
def findLength(arr):
n = len(arr)
res = 0
for i in range(n):
# Keep track of count of 0s and 1s
cnt0 = 0
cnt1 = 0
for j in range(i, n):
if arr[j] == 1:
cnt1 += 1
else:
cnt0 += 1
# Update res if we found a larger subarray with
# count of 1s one greater than count of 0s
if cnt1 - cnt0 == 1:
res = max(res, j - i + 1)
return res
if __name__ == "__main__":
arr = [0, 1, 1, 0, 0, 1]
print(findLength(arr))
C#
// C# Code to find the length of longest subarray
// having count of 1's one more than count of 0's
// by iterating over all subarrays
using System;
class GfG {
static int FindLength(int[] arr) {
int n = arr.Length;
int res = 0;
for (int i = 0; i < n; i++) {
// Keep track of count of 0s and 1s
int cnt0 = 0, cnt1 = 0;
for (int j = i; j < n; j++) {
if (arr[j] == 1)
cnt1++;
else
cnt0++;
// Update res if we found a larger subarray with
// count of 1s one greater than count of 0s
if (cnt1 - cnt0 == 1) {
res = Math.Max(res, j - i + 1);
}
}
}
return res;
}
static void Main() {
int[] arr = { 0, 1, 1, 0, 0, 1 };
Console.WriteLine(FindLength(arr));
}
}
JavaScript
// JavaScript Code to find the length of longest subarray
// having count of 1's one more than count of 0's
// by iterating over all subarrays
function findLength(arr) {
let n = arr.length;
let res = 0;
for (let i = 0; i < n; i++) {
// Keep track of count of 0s and 1s
let cnt0 = 0, cnt1 = 0;
for (let j = i; j < n; j++) {
if (arr[j] === 1)
cnt1++;
else
cnt0++;
// Update res if we found a larger subarray with
// count of 1s one greater than count of 0s
if (cnt1 - cnt0 === 1) {
res = Math.max(res, j - i + 1);
}
}
}
return res;
}
// Driver Code
const arr = [0, 1, 1, 0, 0, 1];
console.log(findLength(arr));
[Expected Approach] Using Hash Map or Dictionary - O(n) Time and O(n) Space
The idea is to transform the array by replacing all 0s with -1s, turning the problem into finding the longest subarray with a sum of 1. Now, maintain a running prefix sum while iterating through the array and use a hash map to store the first occurrence of each prefix sum.
For each index, we check if the (prefix sum - 1) exists in the hash map. If it does, the subarray from the previous occurrence to the current index has a sum of 1. The maximum length among such subarrays will be our final answer.
C++
// C++ Code to find the length of longest subarray
// having count of 1's one more than count of 0's
// using prefix sum and hash map
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int findLength(vector<int> &arr) {
int n = arr.size();
unordered_map<int, int> prefIdx;
int sum = 0, res = 0;
for (int i = 0; i < n; i++) {
// consider 0 as -1
sum += (arr[i] == 0 ? -1 : 1);
// when subarray starts from index 0
if (sum == 1)
res = i + 1;
// make an entry for sum if it is not
// present in the hash map
else if (prefIdx.find(sum) == prefIdx.end())
prefIdx[sum] = i;
// check if (sum - 1) is present in prefIdx
// or not
if (prefIdx.find(sum - 1) != prefIdx.end()) {
if (res < (i - prefIdx[sum - 1]))
res = (i - prefIdx[sum - 1]);
}
}
return res;
}
int main() {
vector<int> arr = { 0, 1, 1, 0, 0, 1 };
cout << findLength(arr);
return 0;
}
Java
// Java Code to find the length of longest subarray
// having count of 1's one more than count of 0's
// using prefix sum and hash map
import java.util.*;
class GfG {
static int findLength(int[] arr) {
Map<Integer, Integer> prefIdx = new HashMap<>();
int sum = 0, res = 0;
for (int i = 0; i < arr.length; i++) {
// consider 0 as -1
sum += (arr[i] == 0 ? -1 : 1);
// when subarray starts from index 0
if (sum == 1)
res = i + 1;
// make an entry for sum if it is not
// present in the hash map
else if (!prefIdx.containsKey(sum))
prefIdx.put(sum, i);
// check if (sum - 1) is present in prefIdx
// or not
if (prefIdx.containsKey(sum - 1)) {
if (res < (i - prefIdx.get(sum - 1)))
res = (i - prefIdx.get(sum - 1));
}
}
return res;
}
public static void main(String[] args) {
int[] arr = { 0, 1, 1, 0, 0, 1 };
System.out.println(findLength(arr));
}
}
Python
# Python Code to find the length of longest subarray
# having count of 1's one more than count of 0's
# using prefix sum and dictionary
def findLength(arr):
n = len(arr)
prefIdx = {}
sum = 0
res = 0
for i in range(n):
# consider 0 as -1
sum += -1 if arr[i] == 0 else 1
# when subarray starts from index 0
if sum == 1:
res = i + 1
# make an entry for sum if it is not
# present in the hash map
elif sum not in prefIdx:
prefIdx[sum] = i
# check if (sum - 1) is present in prefIdx
# or not
if sum - 1 in prefIdx:
if res < (i - prefIdx[sum - 1]):
res = i - prefIdx[sum - 1]
return res
if __name__ == "__main__":
arr = [0, 1, 1, 0, 0, 1]
print(findLength(arr))
C#
// C# Code to find the length of longest subarray
// having count of 1's one more than count of 0's
// using prefix sum and hash map
using System;
using System.Collections.Generic;
class GfG {
static int FindLength(int[] arr) {
int n = arr.Length;
Dictionary<int, int> prefIdx = new Dictionary<int, int>();
int sum = 0, res = 0;
for (int i = 0; i < n; i++) {
// consider 0 as -1
sum += (arr[i] == 0 ? -1 : 1);
// when subarray starts from index 0
if (sum == 1)
res = i + 1;
// make an entry for sum if it is not
// present in the hash map
else if (!prefIdx.ContainsKey(sum))
prefIdx[sum] = i;
// check if (sum - 1) is present in prefIdx
// or not
if (prefIdx.ContainsKey(sum - 1)) {
if (res < (i - prefIdx[sum - 1]))
res = i - prefIdx[sum - 1];
}
}
return res;
}
static void Main() {
int[] arr = { 0, 1, 1, 0, 0, 1 };
Console.WriteLine(FindLength(arr));
}
}
JavaScript
// JavaScript Code to find the length of longest subarray
// having count of 1's one more than count of 0's
// using prefix sum and hash map
function findLength(arr) {
let n = arr.length;
let prefIdx = new Map();
let sum = 0, res = 0;
for (let i = 0; i < n; i++) {
// consider 0 as -1
sum += (arr[i] === 0 ? -1 : 1);
// when subarray starts from index 0
if (sum === 1)
res = i + 1;
// make an entry for sum if it is not
// present in the hash map
else if (!prefIdx.has(sum))
prefIdx.set(sum, i);
// check if (sum - 1) is present in prefIdx
// or not
if (prefIdx.has(sum - 1)) {
if (res < (i - prefIdx.get(sum - 1)))
res = i - prefIdx.get(sum - 1);
}
}
return res;
}
// Driver Code
let arr = [0, 1, 1, 0, 0, 1];
console.log(findLength(arr));
Similar Reads
Longest subarray with GCD greater than 1 Given an array arr[] consisting of N integers, the task is to find the maximum length of subarray having the Greatest Common Divisor (GCD) of all the elements greater than 1. Examples: Input: arr[] = {4, 3, 2, 2}Output: 2Explanation:Consider the subarray {2, 2} having GCD as 2(> 1) which is of ma
15+ min read
Longest Subarray with 0 Sum Given an array arr[] of size n, the task is to find the length of the longest subarray with sum equal to 0.Examples:Input: arr[] = {15, -2, 2, -8, 1, 7, 10, 23}Output: 5Explanation: The longest subarray with sum equals to 0 is {-2, 2, -8, 1, 7}Input: arr[] = {1, 2, 3}Output: 0Explanation: There is n
10 min read
Longest Subarray With Equal Number of 0s and 1s Given an array arr[] containing only 0s and 1s, find the longest subarray which contains equal no of 0s and 1s.Examples: Input: arr[] = [1, 0, 1, 1, 1, 0, 0]Output: 6Explanation: arr[1 ... 6] is the longest subarray with three 0s and three 1s.Input: arr[] = [0, 0, 1, 1, 0]Output: 4Explanation: arr[0
10 min read
Longest subarray with all elements same Given an array arr[] of size N, the task is to find the largest subarray which consists of all equal elements.Examples: Input: arr[] = {1, 1, 2, 2, 2, 3, 3}; Output: 3 Explanation: Longest subarray with equal elements is {2, 2, 2}Input: arr[] = {1, 1, 2, 2, 2, 3, 3, 3, 3}; Output: 4 Explanation: Lon
4 min read
Largest subarray with GCD one There is an array with n elements. Find length of the largest subarray having GCD equal to 1. If no subarray with GCD 1, then print -1. Examples : Input : 1 3 5 Output : 3 Input : 2 4 6 Output :-1 Recommended PracticeLargest subarray with GCD oneTry It! A simple solution is to consider every subarra
6 min read