Open In App

Count Substrings that can be made of length 1 by replacing “01” or “10” with 1 or 0

Last Updated : 16 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary string S of length N, the task is to find the number of pairs of integers [L, R] 1 ≤ L < R ≤ N such that S[L . . . R] (the substring of S from L to R) can be reduced to 1 length string by replacing substrings “01” or “10” with “1” and “0” respectively.

Examples:

Input: S = “0110”
Output: 4
Explanation: The 4 substrings are 01, 10, 110, 0110.

Input: S = “00000”
Output: 0

 

Approach: The solution is based on the following mathematical idea:

We can solve this based on the exclusion principle. Instead of finding possible pairs find the number of impossible cases and subtract that from all possible substrings (i.e. N*(N+1)/2 ).

How to find impossible cases?

When s[i] and s[i-1] are same, then after reduction it will either become “00” or “11”. In both cases, the substring cannot be reduced to length 1. So substring from 0 to i, from 1 to i, . . . cannot be made to have length 1. That count of substrings is i.

Follow the below steps to solve the problem:

  • Initialize answer ans = N * (N + 1) / 2
  • Run a loop from i = 1 to N – 1
    • If S[i] is equal to S[i – 1], then subtract i from ans.
  • Return ans – N (because there are N substrings having length 1).

Below is the implementation of the above approach.

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
#define ll long long
using namespace std;
 
// Function to return number of
// substring
ll find(string Str)
{
 
    ll n = Str.size();
 
    ll ans = n * (n + 1) / 2;
 
    for (ll i = 1; i < n; i++) {
        if (Str[i] == Str[i - 1])
            ans -= i;
    }
 
    return ans - n;
}
 
// Driver code
int main()
{
    string S = "0110";
 
    // Function Call
    cout << find(S) << endl;
    return 0;
}


Java




// Java code to implement the approach
import java.io.*;
 
class GFG {
    // Function to return number of
    // substring
    public static long find(String Str)
    {
 
        int n = Str.length();
 
        long ans = n * (n + 1) / 2;
 
        for (int i = 1; i < n; i++) {
            if (Str.charAt(i) == Str.charAt(i - 1))
                ans -= i;
        }
 
        return ans - n;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String S = "0110";
 
        // Function Call
        System.out.println(find(S));
    }
}
 
// This code is contributed by Rohit Pradhan


Python3




# Pyrthon3 code to implement the approach
 
# Function to return number of
# substring
def find(Str):
    n = len(Str)
    ans = n * (n + 1) / 2
 
    for i in range(0, n):
        if (Str[i] == Str[i - 1]):
            ans -= i;
 
    return ans - n
 
# Driver Code
if __name__ == "__main__":
    S = "0110"
    print(int(find(S)));
 
    # This code is contributed by hrithikgarg03188.


C#




// C# code to implement the approach
 
using System;
 
public class GFG {
 
    // Function to return number of substring
    public static long find(String Str)
    {
 
        int n = Str.Length;
 
        long ans = n * (n + 1) / 2;
 
        for (int i = 1; i < n; i++) {
            if (Str[i] == Str[i - 1])
                ans -= i;
        }
 
        return ans - n;
    }
 
    static public void Main()
    {
 
        // Code
        String S = "0110";
 
        // Function Call
        Console.WriteLine(find(S));
    }
}
 
// This code is contributed by lokeshmvs21.


Javascript




<script>
    // JavaScript code for the above approach
 
    // Function to return number of
    // substring
    function find(Str)
    {
 
        let n = Str.length;
 
        let ans = n * (n + 1) / 2;
 
        for (let i = 1; i < n; i++) {
            if (Str[i] == Str[i - 1])
                ans -= i;
        }
 
        return ans - n;
    }
 
    // Driver Code
     
    let S = "0110";
 
     // Function Call
    document.write(find(S));
 
// This code is contributed by sanjoy_62.
</script>


Output

4

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



Similar Reads

Count N-length arrays made from first M natural numbers whose subarrays can be made palindromic by replacing less than half of its elements
Given two integer N and M, the task is to find the count of arrays of size N with elements from the range [1, M] in which all subarrays of length greater than 1 can be made palindromic by replacing less than half of its elements i.e., floor(length/2). Examples: Input: N = 2, M = 3Output: 6Explanation:There are 9 arrays possible of length 2 using va
4 min read
Lexicographically smallest permutation of a string that can be reduced to length K by removing K-length prefixes from palindromic substrings of length 2K
Given a binary string str of length N, and an integer K, the task is to find the lexicographically smallest permutation of the string str that can be reduced to length K by removal of every K-length prefix from palindromic substrings of length 2K. If no such permutation exists, print "Not Possible". Examples: Input: str = "0000100001100001”, K = 4O
14 min read
Check if any subarray can be made palindromic by replacing less than half of its elements
Given an array arr[] of size N, the task is to check if any subarray from the given array can be made a palindrome by replacing less than half of its elements (i.e. floor[length/2]) by any other element of the subarray. Examples: Input: arr[] = {2, 7, 4, 6, 7, 8}Output: YesExplanation: Among all subarrays of this array, subarray {7, 4, 6, 7} requir
7 min read
Check if characters of a string can be made non-decreasing by replacing '?'s
Given a string S of length N consisting of lowercase English alphabets and '?', the task is to check if it is possible to make the string non-decreasing by replacing all the '?' characters with English alphabets. If found to be true, print "Yes". Otherwise, print "No". Examples: Input: S = "abb?xy?" Output: YesExplanation:Replacing the '?'s at inde
6 min read
Check if all array elements can be made divisible by K by replacing array elements with sum of pairs
Given an array arr[] of size N and a positive integer K, the task is to make every element of the array divisible by K by repeatedly selecting a pair of indices (i, j) and perform arr[i] = arr[i] + arr[j]. Examples: Input: arr[] = {3, 6, 3}, K = 6Output: TrueExplanation: Update arr[0] = arr[0] + arr[0].Update arr[2] = arr[2] + arr[2] Input: arr[] =
7 min read
Check if GCD of Array can be made greater than 1 by replacing pairs with their products
Given three integers L, R, and K. Consider an array arr[] consisting of all the elements from L to R, the task is to check whether the GCD of the array can be made greater than 1 using at most K operations. An operation is defined below: Choose any two numbers from the arrayRemove them from the arrayInsert their product back into the array Examples
7 min read
Check if GCD of [L, R] can be made &gt;1 by replacing pairs with their product at most K times
Given a range [L, R] and an integer K, the task is to check if it is possible to make the GCD of all integers in the given range more than 1 using at most K operations wherein each operation replace any two integers in the range with their product. Examples: Input: L = 1, R = 5, K = 3 .Output: YesExplanation: All the integers in the given range are
5 min read
Check if String can be made Palindrome by replacing characters in given pairs
Given a string str and K pair of characters, the task is to check if string str can be made Palindrome, by replacing one character of each pair with the other. Examples: Input: str = "geeks", K = 2, pairs = [["g", "s"], ["k", "e"]]Output: TrueExplanation: Swap 's' of "geeks" with 'g' using pair ['g', 's'] = "geekg"Swap 'k' of "geekg" with 'e' using
9 min read
Check if Array can be made strictly increasing by replacing element with Average of adjacents
Given an array A[] of size N, the task is to check whether the sequence can be made strictly increasing by performing the following operation any number of times(0 or more): Select any two adjacent elements Ai and Ai+1 and replace one of them with (Ai + Ai+1) / 2 (a real number, i.e. without rounding). Examples: Input: A[] = {1, 2, 2}Output: Yes
Ex
4 min read
Check if Arrays can be made equal by Replacing elements with their number of Digits
Given two arrays A[] and B[] of length N, the task is to check if both arrays can be made equal by performing the following operation at most K times: Choose any index i and either change Ai to the number of digits Ai have or change Bi to the number of digits Bi have. Examples: Input: N = 4, K = 1, A = [1, 2, 3, 4], B = [1, 2, 3, 5]Output: UnequalE
10 min read
Practice Tags :