Open In App

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++
Java Python3 JavaScript C#

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++
Java Python3 C# JavaScript

Output: 
2

 

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


Next Article
Article Tags :
Practice Tags :

Similar Reads