Open In App

Longest Subarray with an Extra 1

Last Updated : 11 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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));

Output
5

[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));

Output
5




Next Article
Article Tags :
Practice Tags :

Similar Reads