Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Minimum LCM of all subarrays of length at least 2
Next article icon

Minimum length subarray of 1s in a Binary Array

Last Updated : 28 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given binary array. The task is to find the length of subarray with minimum number of 1s.
Note: It is guaranteed that there is atleast one 1 present in the array.
Examples : 
 

Input : arr[] = {1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1} 
Output : 3 
Minimum length subarray of 1s is {1, 1}.
Input : arr[] = {0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1} 
Output : 1  

Simple Solution: A simple solution is to consider every subarray and count 1’s in every subarray. Finally return return size of minimum length subarray of 1s.

C++




#include <bits/stdc++.h>
using namespace std;
 
int subarrayWithMinOnes(int arr[], int n)
{
    int ans = INT_MAX;
 
    // consider all subarrays starting from index i
    for (int i = 0; i < n; i++) {
        // consider all subarrays ending at index j
        for (int j = i+1; j < n; j++) {
            int count = 0;
            bool flag = true;
            // count the number of 1s in the current subarray
            for (int k = i; k <= j; k++) {
                if (arr[k] != 1) {
                    flag = false;
                    break;
                }
                else
                    count++;
            }
            // if current subarray has all 1s, update ans
            if (flag)
                ans = min(ans, count);
        }
    }
    return ans;
}
 
int main()
{
    int arr[] = { 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << subarrayWithMinOnes(arr, n) << endl;
    return 0;
}
//This code is conntributed by Naveen Gujjar
 
 

Java




import java.util.*;
 
public class Main {
    public static int subarrayWithMinOnes(int[] arr, int n) {
        int ans = Integer.MAX_VALUE;
 
        // consider all subarrays starting from index i
        for (int i = 0; i < n; i++) {
            // consider all subarrays ending at index j
            for (int j = i+1; j < n; j++) {
                int count = 0;
                boolean flag = true;
                // count the number of 1s in the current subarray
                for (int k = i; k <= j; k++) {
                    if (arr[k] != 1) {
                        flag = false;
                        break;
                    }
                    else
                        count++;
                }
                // if current subarray has all 1s, update ans
                if (flag)
                    ans = Math.min(ans, count);
            }
        }
        return ans;
    }
 
    public static void main(String[] args) {
        int[] arr = { 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1 };
        int n = arr.length;
        System.out.println(subarrayWithMinOnes(arr, n));
    }
}
 
 

Python3




def subarrayWithMinOnes(arr, n):
    ans = float('inf')
 
    # consider all subarrays starting from index i
    for i in range(n):
       
        # consider all subarrays ending at index j
        for j in range(i+1, n):
            count = 0
            flag = True
             
            # count the number of 1s in the current subarray
            for k in range(i, j+1):
                if arr[k] != 1:
                    flag = False
                    break
                else:
                    count += 1
                     
            # if current subarray has all 1s, update ans
            if flag:
                ans = min(ans, count)
    return ans
 
arr = [1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1]
n = len(arr)
print(subarrayWithMinOnes(arr, n))
 
 

Javascript




function subarrayWithMinOnes(arr, n) {
    let ans = Infinity;
    for (let i = 0; i < n; i++) {
        for (let j = i+1; j < n; j++) {
            let count = 0;
            let flag = true;
            for (let k = i; k <= j; k++) {
                if (arr[k] !== 1) {
                    flag = false;
                    break;
                } else {
                    count++;
                }
            }
            if (flag) {
                ans = Math.min(ans, count);
            }
        }
    }
    return ans;
}
 
let arr = [1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1];
let n = arr.length;
console.log(subarrayWithMinOnes(arr, n));
 
 

C#




using System;
 
class Program {
    static int SubarrayWithMinOnes(int[] arr, int n)
    {
        int ans = int.MaxValue;
        // consider all subarrays starting from index i
        for (int i = 0; i < n; i++) {
            // consider all subarrays ending at index j
            for (int j = i + 1; j < n; j++) {
                int count = 0;
                bool flag = true;
                // count the number of 1s in the current
                // subarray
                for (int k = i; k <= j; k++) {
                    if (arr[k] != 1) {
                        flag = false;
                        break;
                    }
                    else
                        count++;
                }
                // if current subarray has all 1s, update
                // ans
                if (flag)
                    ans = Math.Min(ans, count);
            }
        }
        return ans;
    }
 
    static void Main(string[] args)
    {
        int[] arr = { 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1 };
        int n = arr.Length;
        Console.WriteLine(SubarrayWithMinOnes(arr, n));
    }
}
// This code is contributed by sarojmcy2e
 
 
Output
2

Time complexity: O(n^3)
Auxiliary Space: O(1)

 
Efficient Solution: An efficient solution is traverse array from left to right. If we see a 1, we increment count. If we see a 0, and count of 1s so far is positive, calculate minimum of count and result and reset count to zero.
Below is the implementation of the above approach:
 

C++




// C++ program to count minimum length
// subarray of 1's in a binary array.
#include <bits/stdc++.h>
using namespace std;
 
// Function to count minimum length subarray
// of 1's in binary array arr[0..n-1]
int getMinLength(bool arr[], int n)
{
    int count = 0; // initialize count
    int result = INT_MAX; // initialize result
 
    for (int i = 0; i < n; i++) {
        if (arr[i] == 1) {
            count++;
        }
        else {
            if (count != 0)
                result = min(result, count);
            count = 0;
        }
    }
 
    return result;
}
 
// Driver code
int main()
{
    bool arr[] = { 1, 1, 0, 0, 1, 1, 1, 0,
                   1, 1, 1, 1 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << getMinLength(arr, n) << endl;
 
    return 0;
}
 
 

Java




// Java program to count minimum length
// subarray of 1's in a binary array.
import java.io.*;
 
class GFG
{
     
// Function to count minimum length subarray
// of 1's in binary array arr[0..n-1]
static int getMinLength(double arr[], int n)
{
    int count = 0; // initialize count
    int result = Integer.MAX_VALUE; // initialize result
 
    for (int i = 0; i < n; i++)
    {
        if (arr[i] == 1)
        {
            count++;
        }
        else
        {
            if (count != 0)
                result = Math.min(result, count);
            count = 0;
        }
    }
 
    return result;
}
 
// Driver code
public static void main (String[] args)
{
    double arr[] = { 1, 1, 0, 0, 1, 1, 1, 0,
                1, 1, 1, 1 };
    int n = arr.length;
    System.out.println (getMinLength(arr, n));
 
}
}
 
// This code is contributed by ajit.
 
 

Python3




# Python program to count minimum length
# subarray of 1's in a binary array.
import sys
 
# Function to count minimum length subarray
# of 1's in binary array arr[0..n-1]
def getMinLength(arr, n):
    count = 0; # initialize count
    result = sys.maxsize ; # initialize result
 
    for i in range(n):
        if (arr[i] == 1):
            count+=1;
        else:
            if(count != 0):
                result = min(result, count);
            count = 0;
 
    return result;
 
# Driver code
arr = [ 1, 1, 0, 0, 1, 1, 1, 0,
                1, 1, 1, 1 ];
 
n = len(arr);
 
print(getMinLength(arr, n));
 
# This code is contributed by Rajput-Ji
 
 

C#




// C# program to count minimum length
// subarray of 1's in a binary array.
using System;
 
class GFG
{
     
// Function to count minimum length subarray
// of 1's in binary array arr[0..n-1]
static int getMinLength(double []arr, int n)
{
    int count = 0; // initialize count
    int result = int.MaxValue; // initialize result
 
    for (int i = 0; i < n; i++)
    {
        if (arr[i] == 1)
        {
            count++;
        }
        else
        {
            if (count != 0)
                result = Math.Min(result, count);
            count = 0;
        }
    }
 
    return result;
}
 
// Driver code
static public void Main ()
{
    double []arr = { 1, 1, 0, 0, 1, 1,
                     1, 0, 1, 1, 1, 1 };
    int n = arr.Length;
    Console.WriteLine(getMinLength(arr, n));
}
}
 
// This code is contributed by Tushil..
 
 

Javascript




<script>
 
// javascript program to count minimum length
// subarray of 1's in a binary array.
  
// Function to count minimum length subarray
// of 1's in binary array arr[0..n-1]
function getMinLength(arr, n)
{
// initialize count
    var count = 0;
// initialize result
    var result = Number.MAX_VALUE;
 
    for (i = 0; i < n; i++)
    {
        if (arr[i] == 1)
        {
            count++;
        }
        else
        {
            if (count != 0)
                result = Math.min(result, count);
            count = 0;
        }
    }
 
    return result;
}
 
// Driver code
var arr = [ 1, 1, 0, 0, 1, 1, 1, 0,
           1, 1, 1, 1 ];
var n = arr.length;
document.write(getMinLength(arr, n));
 
// This code is contributed by Amit Katiyar
 
</script>
 
 
Output: 
2

 

Time Complexity: O(N) 
Auxiliary Space: O(1)



Next Article
Minimum LCM of all subarrays of length at least 2

S

Striver
Improve
Article Tags :
  • Arrays
  • DSA
  • binary-representation
  • subarray
Practice Tags :
  • Arrays

Similar Reads

  • Count Subarrays of 1 in Binary Array
    Given an array arr[] of size N, the array contains only 1s and 0s, and the task is to return the count of the total number of subarrays where all the elements of the subarrays are 1. Examples: Input: N = 4, arr[] = {1, 1, 1, 0}Output: 6Explanation: Subarrays of 1 will look like the following: [1], [
    13 min read
  • Minimum Subarray reversals to sort given Binary Array
    Given a binary array A[] of size N, the task is to find the minimum number of subarrays that need to be reversed to sort the binary array. Examples: Input: N = 4, A[]: {1, 0 , 0, 1} Output: 1Explanation: Reverse the array from 0 to 2 to change the array to {0, 0, 1, 1} Input: N = 4, A[]: {1, 0, 1 ,
    5 min read
  • Minimum LCM of all subarrays of length at least 2
    Given an array arr[] of N positive integers. The task is to find the minimum LCM of all subarrays of size greater than 1. Examples: Input: arr[] = { 3, 18, 9, 18, 5, 15, 8, 7, 6, 9 } Output: 15 Explanation: LCM of subarray {5, 15} is minimum which is 15. Input: arr[] = { 4, 8, 12, 16, 20, 24 } Outpu
    11 min read
  • Minimum Subarray flips required to convert all elements of a Binary Array to K
    The problem statement is asking for the minimum number of operations required to convert all the elements of a given binary array arr[] to a specified value K, where K can be either 0 or 1. The operations can be performed on any index X of the array, and the operation is to flip all the elements of
    8 min read
  • Maximum Length Bitonic Subarray
    Given an array arr[0 ... n-1] of n positive integers, a subarray arr[i ... j] is bitonic if there exists an index k (i ≤ k ≤ j) such that arr[i] ≤ arr[i+1] ≤ ... ≤ arr[k] and arr[k] ≥ arr[k+1] ≥ ... ≥ arr[j].Find the length of the longest bitonic subarray. Examples Input: arr[] = [12, 4, 78, 90, 45,
    13 min read
  • Minimum number of 1's to be replaced in a binary array
    Given a binary array arr[] of zero's and one's only. The task is to find the minimum number of one's to be changed to zero such if there exist any index [Tex]i [/Tex]in the array such that arr[i] = 0 then arr[i-1] and arr[i+1] both should not be equals to [Tex]1 [/Tex]at the same time. That is, for
    5 min read
  • Count subarrays consisting of only 0's and only 1's in a binary array
    Given a binary array consisting of only zeroes and ones. The task is to find: The number of subarrays which has only 1 in it.The number of subarrays which has only 0 in it.Examples: Input: arr[] = {0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1} Output: The number of subarrays consisting of 0 only: 7 The number
    14 min read
  • Maximize number of 1s by flipping a subarray
    Given a binary array, the task is to find the maximum number of 1's in the array with at most one flip of a subarray allowed. A flip operation switches all 0s to 1s and 1s to 0s. Examples: Input : arr[] = [0, 1, 0, 0, 1, 1, 0]Output : 5Explanation: Flip the subarray from index 2 to 3. Array will bec
    10 min read
  • Count 1's in a sorted binary array
    Given a binary array arr[] of size n, which is sorted in non-increasing order, count the number of 1's in it. Examples: Input: arr[] = [1, 1, 0, 0, 0, 0, 0]Output: 2Explanation: Count of the 1's in the given array is 2. Input: arr[] = [1, 1, 1, 1, 1, 1, 1]Output: 7 Input: arr[] = [0, 0, 0, 0, 0, 0,
    8 min read
  • Minimum common element in subarrays of all possible lengths
    Given an array arr[] consisting of N integers from the range [1, N]( repetition allowed ), the task is to find the minimum common element for each possible subarray length. If no such element exists for any particular length of the subarray, then print -1. Examples: Input: arr[] = {1, 3, 4, 5, 6, 7}
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences