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
  • Practice Combinatorics
  • MCQs on Combinatorics
  • Basics of Combinatorics
  • Permutation and Combination
  • Permutation Vs Combination
  • Binomial Coefficient
  • Calculate nPr
  • Calculate nCr
  • Pigeonhole Principle
  • Principle of Inclusion-Exclusion
  • Catalan Number
  • Lexicographic Rank
  • Next permutation
  • Previous Permutation
Open In App
Next Article:
Count of substrings of a binary string containing K ones
Next article icon

Count of K length subarrays containing only 1s in given Binary String

Last Updated : 04 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary string str, the task is to find the count of K length subarrays containing only 1s.

Examples:

Input: str = "0101000", K=1
Output: 2
Explanation: 0101000 -> There are 2 subarrays with 1 ones

Input: str = "11111001", K=3
Output: 3

 

Approach: The task can be solved by keeping track of the group sizes of consecutive ones. Once, we get the groupSize, we can deduce that number of possible subarrays of length k, and all 1s, are groupSize - k + 1.

Follow the below steps to solve the problem:

  • Iterate over the binary string from the start
  • Increment the count, if 1 is encountered, and at a point where 0 comes.
  • Store the current count to get the groupSize of consecutive 1s, and re-initialize the count to 0.
  • Add the count of possible subarrays of size k in this groupSize using relation groupSize - k + 1
  • Return the final sum of count.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Function to find the count of all possible // k length subarrays int get(string s, int k) {     // Add dummy character at last to handle     // edge cases, where string ends with '1'     s += '0';     int n = s.length();      int cnt = 0, ans = 0;     for (int i = 0; i < n; i++) {         if (s[i] == '1')             cnt++;         else {             if (cnt >= k) {                 ans += (cnt - k + 1);             }             cnt = 0;         }     }     return ans; }  // Driver code int main() {     string str = "0101000";     int K = 1;     cout << get(str, K) << endl;     return 0; } 
Java
// Java program for the above approach import java.util.*;  class GFG{  // Function to find the count of all possible // k length subarrays static int get(String s, int k) {        // Add dummy character at last to handle     // edge cases, where String ends with '1'     s += '0';     int n = s.length();      int cnt = 0, ans = 0;     for (int i = 0; i < n; i++) {         if (s.charAt(i) == '1')             cnt++;         else {             if (cnt >= k) {                 ans += (cnt - k + 1);             }             cnt = 0;         }     }     return ans; }  // Driver code public static void main(String[] args) {     String str = "0101000";     int K = 1;     System.out.print(get(str, K) +"\n"); } }  // This code is contributed by Rajput-Ji 
Python3
# Python code for the above approach  # Function to find the count of all possible # k length subarrays def get(s, k):      # Add dummy character at last to handle     # edge cases, where string ends with '1'     s += '0'     n = len(s)      cnt = 0     ans = 0     for i in range(n):         if (s[i] == '1'):             cnt += 1         else:             if (cnt >= k):                 ans += (cnt - k + 1)             cnt = 0     return ans  # Driver code str = "0101000" K = 1 print(get(str, K))  # This code is contributed by Saurabh Jaiswal 
C#
// C# program for the above approach using System; class GFG {        // Function to find the count of all possible     // k length subarrays     static int get(string s, int k)     {                // Add dummy character at last to handle         // edge cases, where string ends with '1'         s += '0';         int n = s.Length;          int cnt = 0, ans = 0;         for (int i = 0; i < n; i++) {             if (s[i] == '1')                 cnt++;             else {                 if (cnt >= k) {                     ans += (cnt - k + 1);                 }                 cnt = 0;             }         }         return ans;     }      // Driver code     public static void Main()     {         string str = "0101000";         int K = 1;         Console.WriteLine(get(str, K));     } }  // This code is contributed by ukasp. 
JavaScript
<script>     // JavaScript code for the above approach      // Function to find the count of all possible     // k length subarrays     function get(s, k)      {            // Add dummy character at last to handle       // edge cases, where string ends with '1'       s += '0';       let n = s.length;        let cnt = 0, ans = 0;       for (let i = 0; i < n; i++) {         if (s[i] == '1')           cnt++;         else {           if (cnt >= k) {             ans += (cnt - k + 1);           }           cnt = 0;         }       }       return ans;     }      // Driver code     let str = "0101000";     let K = 1;     document.write(get(str, K) + '<br>');    // This code is contributed by Potta Lokesh   </script> 

 
 

Output
2

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


 


Next Article
Count of substrings of a binary string containing K ones
author
sauarbhyadav
Improve
Article Tags :
  • Strings
  • Combinatorial
  • Algo Geek
  • DSA
  • Algo-Geek 2021
  • binary-string
  • subarray
Practice Tags :
  • Combinatorial
  • Strings

Similar Reads

  • Count of K length subarrays containing only 1s in given Binary String | Set 2
    Given binary string str, the task is to find the count of K length subarrays containing only 1s. Examples Input: str = "0101000", K=1Output: 2Explanation: 0101000 -> There are 2 subarrays of length 1 containing only 1s. Input: str = "11111001", K=3Output: 3 Approach: The given problem can also be
    4 min read
  • Find all K length subarrays containing only 1s in given Binary String
    Given a binary string str[], the task is to find all possible K length subarrays containing only 1s and print their starting and ending index. Examples: Input: str = "0101000", K=1Output: 1 13 3Explanation: Substrings at positions 1 and 3 are the substrings with value 1. Input: str = "11111001", K=3
    6 min read
  • Count of substrings of a Binary string containing only 1s
    Given a binary string of length N, we need to find out how many substrings of this string contain only 1s. Examples: Input: S = "0110111"Output: 9Explanation:There are 9 substring with only 1's characters. "1" comes 5 times. "11" comes 3 times. "111" comes 1 time. Input: S = "000"Output: 0 The_Appro
    6 min read
  • Count of substrings of a binary string containing K ones
    Given a binary string of length N and an integer K, we need to find out how many substrings of this string are exist which contains exactly K ones. Examples: Input : s = “10010” K = 1 Output : 9 The 9 substrings containing one 1 are, “1”, “10”, “100”, “001”, “01”, “1”, “10”, “0010” and “010”Recommen
    7 min read
  • Count of binary strings of given length consisting of at least one 1
    Given an integer N, the task is to print the number of binary strings of length N which at least one '1'. Examples: Input: 2 Output: 3 Explanation: "01", "10" and "11" are the possible strings Input: 3 Output: 7 Explanation: "001", "011", "010", "100", "101", "110" and "111" are the possible strings
    3 min read
  • Count ways to generate Binary String not containing "0100" Substring
    Given the number N, count the number of ways to create a binary string (the string that contains characters as zero or one) of size N such that it does not contain "0100" as a substring. A substring is a contiguous sequence of characters within a string. Examples: Input: N = 4Output: 15Explanation:
    15+ min read
  • Count of setbits in bitwise OR of all K length substrings of given Binary String
    Given a binary string str of length N, the task is to find the number of setbits in the bitwise OR of all the K length substrings of string str. Examples: Input: N = 4, K = 3, str = "1111"Output: 3Explanation: All 3-sized substrings of S are:"111" and "111". The OR of these strings is "111". Therefo
    8 min read
  • Count N-length Binary Strings consisting of "11" as substring
    Given a positive integer N, the task is to find the number of binary strings of length N which contains "11" as a substring. Examples: Input: N = 2Output: 1Explanation: The only string of length 2 that has "11" as a substring is "11". Input: N = 12Output: 3719 Approach: The idea is to derive the num
    8 min read
  • Count of substrings from given Ternary strings containing characters at least once
    Given string str of size N consisting of only 0, 1, and 2, the task is to find the number of substrings that consists of characters 0, 1, and 2 at least once. Examples: Input: str = "0122"Output: 2Explanation:There exists 2 substrings such that the substrings has characters 0, 1, 2 at least once is
    6 min read
  • Count of substrings containing only the given character
    Given a string S and a character C, the task is to count the number of substrings of S that contains only the character C.Examples: Input: S = "0110111", C = '1' Output: 9 Explanation: The substrings containing only '1' are: "1" — 5 times "11" — 3 times "111" — 1 time Hence, the count is 9. Input: S
    6 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