Count Binary Substrings
💻 coding

Count Binary Substrings

1 min read 235 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to count contiguous substrings with equal numbers of consecutive 0's and 1's.
  • 2Examples show that valid substrings must have grouped characters, such as '0011' or '10'.
  • 3The provided solution has a time complexity of O(n) and a space complexity of O(n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to count contiguous substrings with equal numbers of consecutive 0's and 1's."

Count Binary Substrings

Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.

Substrings that occur multiple times are counted the number of times they occur.

Example 1:

Input: "00110011"

Output: 6

Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".

Notice that some of these substrings repeat and are counted the number of times they occur.

Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.

Example 2:

Input: "10101"

Output: 4

Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.

Note:

s.length will be between 1 and 50,000.

s will only consist of "0" or "1" characters.

Solution:

using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode.AskGif.Easy.String
{
 public class CountBinarySubstringsSoln
 {
 public int CountBinarySubstrings(string s)
 {
 var groups = new int[s.Length];
 groups[0] = 1;
 int j = 0;
 for (int i = 1; i < s.Length; i++)
 {
 if(s[i-1] != s[i])
 {
 j++;
 groups[j] = 1;
 }
 else
 {
 groups[j]++;
 }
 }

 int sum = 0;
 for (int i = 1; i < s.Length; i++)
 {
 sum += Math.Min(groups[i - 1], groups[i]);
 }

 return sum;
 }

 
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 10 May 2020 · 1 min read · 235 words

Part of AskGif Blog · coding

You might also like