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 bit flips such that every K consecutive bits contain at least one set bit
Next article icon

Minimum sub-array such that number of 1's in concatenation of binary representation of its elements is at least K

Last Updated : 29 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of non-negative integers and an integer k. The task is to find the minimum length of any sub-array of arr[] such that if all elements of this sub-array are represented in binary notation and concatenated to form a binary string then number of 1's in the resulting string is at least k. If no such sub-array exists then print -1. 

Examples: 

Input: arr[] = {4, 3, 7, 9}, k = 4 
Output: 2 
A possible sub-array is {3, 7}.

Input: arr[] = {1, 2, 4, 8}, k = 2 
Output: 2 
 

Approach: The idea is to use two variables j and i and initialize them to 0 and 1 respectively, and an array count_one which will store the number of one's present in the binary representation of a particular element of the array and a variable sum to store the number of 1's upto ith index and ans to store the minimum length. Now iterate over the array, if the number of 1's of ith or jth element of count_one is equal to k, then update ans as 1, if the sum of number of 1's upto ith element is greater than or equal to k update ans as minimum of ans and (i-j)+1, else if it is less than k then increment j by 1, to increase the value of sum.

Below is the implementation of the approach:  

C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std;  // Finds the sub-array with maximum length int FindSubarray(int arr[], int n, int k) {     // Array which stores number of ones     // present in the binary representation     // of ith element of the array     int count_one[n];      for (int i = 0; i < n; i++) {         count_one[i] = __builtin_popcount(arr[i]);     }      // Sum variable to store sum of     // number of ones     // Initialize it as number of ones     // present in the binary representation     // of 0th element of the array     int sum = count_one[0];      // If there is only a single element     if (n == 1) {         if (count_one[0] >= k)             return 1;         else             return -1;     }      // Stores the minimum length     // of the required sub-array     int ans = INT_MAX;      int i = 1;     int j = 0;      while (i < n) {         // If binary representation of jth         // element of array has 1's equal to k         if (k == count_one[j]) {             ans = 1;             break;         }          // If binary representation of ith         // element of array has 1's equal to k         else if (k == count_one[i]) {             ans = 1;             break;         }          // If sum of number of 1's of         // binary representation of elements upto         // ith element is less than k         else if (sum + count_one[i] < k) {             sum += count_one[i];             i++;         }          // If sum of number of 1's of         // binary representation of elements upto         // ith element is greater than k         else if (sum + count_one[i] > k) {             ans = min(ans, (i - j) + 1);             sum -= count_one[j];             j++;         }          else if (sum + count_one[i] == k) {             ans = min(ans, (i - j) + 1);             sum += count_one[i];             i++;         }     }      if (ans != INT_MAX)         return ans;      else         return -1; }  // Driver code int main() {     int arr[] = { 1, 2, 4, 8 };     int n = sizeof(arr) / sizeof(int);     int k = 2;      cout << FindSubarray(arr, n, k);      return 0; } 
Java
// Java implementation of the approach class GFG {  // Finds the sub-array with maximum length static int FindSubarray(int arr[], int n, int k) {     // Array which stores number of ones     // present in the binary representation     // of ith element of the array     int []count_one = new int[n];      for (int i = 0; i < n; i++)     {         count_one[i] = Integer.bitCount(arr[i]);     }      // Sum variable to store sum of     // number of ones     // Initialize it as number of ones     // present in the binary representation     // of 0th element of the array     int sum = count_one[0];      // If there is only a single element     if (n == 1)      {         if (count_one[0] >= k)             return 1;         else             return -1;     }      // Stores the minimum length     // of the required sub-array     int ans = Integer.MAX_VALUE;      int i = 1;     int j = 0;      while (i < n)      {         // If binary representation of jth         // element of array has 1's equal to k         if (k == count_one[j])          {             ans = 1;             break;         }          // If binary representation of ith         // element of array has 1's equal to k         else if (k == count_one[i])          {             ans = 1;             break;         }          // If sum of number of 1's of         // binary representation of elements upto         // ith element is less than k         else if (sum + count_one[i] < k)         {             sum += count_one[i];             i++;         }          // If sum of number of 1's of         // binary representation of elements upto         // ith element is greater than k         else if (sum + count_one[i] > k)          {             ans = Math.min(ans, (i - j) + 1);             sum -= count_one[j];             j++;         }          else if (sum + count_one[i] == k)          {             ans = Math.min(ans, (i - j) + 1);             sum += count_one[i];             i++;         }     }      if (ans != Integer.MAX_VALUE)         return ans;      else         return -1; }  // Driver code public static void main(String[] args)  {     int arr[] = { 1, 2, 4, 8 };     int n = arr.length;     int k = 2;      System.out.println(FindSubarray(arr, n, k)); } }  // This code is contributed by Princi Singh 
Python3
# Python3 implementation of the approach  import sys;  # Finds the sub-array with maximum length  def FindSubarray(arr, n, k) :       # Array which stores number of ones      # present in the binary representation      # of ith element of the array      count_one = [0] * n;       for i in range(n) :          count_one[i] = bin(arr[i]).count('1');          # Sum variable to store sum of      # number of ones      # Initialize it as number of ones      # present in the binary representation      # of 0th element of the array      sum = count_one[0];       # If there is only a single element      if (n == 1) :                  if (count_one[0] >= k) :             return 1;          else :             return -1;           # Stores the minimum length      # of the required sub-array      ans = sys.maxsize;       i = 1;      j = 0;       while (i < n) :                  # If binary representation of jth          # element of array has 1's equal to k          if (k == count_one[j]) :             ans = 1;              break;                   # If binary representation of ith          # element of array has 1's equal to k          elif (k == count_one[i]) :             ans = 1;             break;                   # If sum of number of 1's of          # binary representation of elements upto          # ith element is less than k          elif (sum + count_one[i] < k) :              sum += count_one[i];              i += 1;                   # If sum of number of 1's of          # binary representation of elements upto          # ith element is greater than k          elif (sum + count_one[i] > k) :              ans = min(ans, (i - j) + 1);              sum -= count_one[j];              j += 1;                   elif (sum + count_one[i] == k) :             ans = min(ans, (i - j) + 1);              sum += count_one[i];              i += 1;       if (ans != sys.maxsize) :         return ans;       else :         return -1;   # Driver code  if __name__ == "__main__" :      arr = [ 1, 2, 4, 8 ];      n = len(arr);      k = 2;       print(FindSubarray(arr, n, k));   # This code is contributed by Ryuga 
C#
// C# implementation of the approach using System;      class GFG {  // Finds the sub-array with maximum length static int FindSubarray(int []arr, int n, int k) {     // Array which stores number of ones     // present in the binary representation     // of ith element of the array     int []count_one = new int[n];     int i = 0;     for (i = 0; i < n; i++)     {         count_one[i] = bitCount(arr[i]);     }      // Sum variable to store sum of     // number of ones     // Initialize it as number of ones     // present in the binary representation     // of 0th element of the array     int sum = count_one[0];      // If there is only a single element     if (n == 1)      {         if (count_one[0] >= k)             return 1;         else             return -1;     }      // Stores the minimum length     // of the required sub-array     int ans = int.MaxValue;      i = 1;     int j = 0;      while (i < n)      {         // If binary representation of jth         // element of array has 1's equal to k         if (k == count_one[j])          {             ans = 1;             break;         }          // If binary representation of ith         // element of array has 1's equal to k         else if (k == count_one[i])          {             ans = 1;             break;         }          // If sum of number of 1's of         // binary representation of elements upto         // ith element is less than k         else if (sum + count_one[i] < k)         {             sum += count_one[i];             i++;         }          // If sum of number of 1's of         // binary representation of elements upto         // ith element is greater than k         else if (sum + count_one[i] > k)          {             ans = Math.Min(ans, (i - j) + 1);             sum -= count_one[j];             j++;         }          else if (sum + count_one[i] == k)          {             ans = Math.Min(ans, (i - j) + 1);             sum += count_one[i];             i++;         }     }      if (ans != int.MaxValue)         return ans;      else         return -1; }  static int bitCount(long x) {     int setBits = 0;     while (x != 0)      {         x = x & (x - 1);         setBits++;     }     return setBits; }  // Driver code public static void Main(String[] args)  {     int []arr = { 1, 2, 4, 8 };     int n = arr.Length;     int k = 2;      Console.WriteLine(FindSubarray(arr, n, k)); } }  // This code is contributed by Rajput-Ji 
JavaScript
<script>  // Javascript implementation of the approach  // Finds the sub-array with maximum length function FindSubarray(arr, n, k) {          // Array which stores number of ones     // present in the binary representation     // of ith element of the array     let count_one = new Array(n);     let i = 0;          for(i = 0; i < n; i++)     {         count_one[i] = bitCount(arr[i]);     }      // Sum variable to store sum of     // number of ones     // Initialize it as number of ones     // present in the binary representation     // of 0th element of the array     let sum = count_one[0];      // If there is only a single element     if (n == 1)      {         if (count_one[0] >= k)             return 1;         else             return -1;     }      // Stores the minimum length     // of the required sub-array     let ans = Number.MAX_VALUE;      i = 1;     let j = 0;      while (i < n)      {                  // If binary representation of jth         // element of array has 1's equal to k         if (k == count_one[j])          {             ans = 1;             break;         }          // If binary representation of ith         // element of array has 1's equal to k         else if (k == count_one[i])          {             ans = 1;             break;         }          // If sum of number of 1's of         // binary representation of elements upto         // ith element is less than k         else if (sum + count_one[i] < k)         {             sum += count_one[i];             i++;         }          // If sum of number of 1's of         // binary representation of elements upto         // ith element is greater than k         else if (sum + count_one[i] > k)          {             ans = Math.min(ans, (i - j) + 1);             sum -= count_one[j];             j++;         }          else if (sum + count_one[i] == k)          {             ans = Math.min(ans, (i - j) + 1);             sum += count_one[i];             i++;         }     }      if (ans != Number.MAX_VALUE)         return ans;     else         return -1; }  function bitCount(x) {     let setBits = 0;          while (x != 0)      {         x = x & (x - 1);         setBits++;     }     return setBits; }  // Driver code let arr = [ 1, 2, 4, 8 ]; let n = arr.length; let k = 2;  document.write(FindSubarray(arr, n, k));  // This code is contributed by divyeshrabadiya07  </script> 

Output: 
2

 

Next Article
Minimum bit flips such that every K consecutive bits contain at least one set bit
author
sakshi_srivastava
Improve
Article Tags :
  • Algorithms
  • C++ Programs
  • Data Structures
  • DSA
  • Arrays
Practice Tags :
  • Algorithms
  • Arrays
  • Data Structures

Similar Reads

  • Minimum bit flips such that every K consecutive bits contain at least one set bit
    Given a binary string S, and an integer K, the task is to find the minimum number of flips required such that every substring of length K contains at least one '1'.Examples: Input: S = "10000001" K = 2 Output: 3 Explanation: We need only 3 changes in string S ( at position 2, 4 and 6 ) so that the s
    8 min read
  • Minimize count of flips required such that no substring of 0s have length exceeding K
    Given a binary string str of length N and an integer K where K is in the range (1 ? K ? N), the task is to find the minimum number of flips( conversion of 0s to 1 or vice versa) required to be performed on the given string such that the resulting string does not contain K or more zeros together. Exa
    6 min read
  • Minimum replacements required to have at most K distinct elements in the array
    Given an array arr[] consisting of N positive integers and an integer K, the task is to find the minimum number of array elements required to be replaced by the other array elements such that the array contains at most K distinct elements. Input: arr[] = { 1, 1, 2, 2, 5 }, K = 2 Output: 1 Explanatio
    13 min read
  • Count of Arrays of size N with elements in range [0, (2^K)-1] having maximum sum & bitwise AND 0
    Given two integers N and K, The task is to find the count of all possible arrays of size N with maximum sum & bitwise AND of all elements as 0. Also, elements should be within the range of 0 to 2K-1. Examples: Input: N = 3, K = 2Output: 9Explanation: 22 - 1 = 3, so elements of arrays should be b
    6 min read
  • Minimum length of Run Length Encoding possible by removing at most K characters from a given string
    Given a string S of length N, consisting of lowercase English alphabets only, the task is to find the minimum possible length of run-length-encoding that can be generated by removing at most K characters from the string S. Examples: Input: S = "abbbcdcdd", N = 9, K = 2 Output: 5 Explanation: One pos
    10 min read
  • Minimum XOR of at most K elements in range [L, R]
    Given three integers L, R, and K, the task is to find the minimum Bitwise XOR of at most K integers between [L, R]. Examples: Input: L = 1, R = 10, K = 3Output: 0Explanation:Choose elements 4, 5, and 1 in the range [1, 10] and the Bitwise XOR of the chosen elements is 0, which is minimum. Input: L =
    15+ min read
  • Minimize the maximum element of N subarrays of size K
    Given an array arr[] and two integers N and K, the task is to choose non-overlapping N subarrays of size K such that the maximum element of all subarrays is minimum.Note: If it is not possible to choose N such subarrays then return -1. Examples: Input: arr[] = {1, 10, 3, 10, 2}, N = 3, K = 1 Output:
    8 min read
  • Shortest subarray to be removed to make all Array elements unique
    Given an array arr[] containing N elements, the task is to remove a subarray of minimum possible length from the given array such that all remaining elements are distinct. Print the minimum possible length of the subarray.Examples: Input: N = 5, arr[] = {1, 2, 1, 2, 3} Output: 2 Explanation: Remove
    12 min read
  • Smallest element present in every subarray of all possible lengths
    Given an array arr[] of length N, the task for every possible length of subarray is to find the smallest element present in every subarray of that length. Examples: Input: N = 10, arr[] = {2, 3, 5, 3, 2, 3, 1, 3, 2, 7}Output: -1-1 3 2 2 2 1 1 1 1Explanation:For length = 1, no element is common in ev
    15+ min read
  • Minimum MEX from all subarrays of length K
    Given an array arr[] consisting of N distinct positive integers and an integer K, the task is to find the minimum MEX from all subarrays of length K. The MEX is the smallest positive integer that is not present in the array. Examples: Input: arr[] = {1, 2, 3}, K = 2Output: 1Explanation:All subarrays
    7 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