Queries to flip characters of a binary string in given range
Last Updated :
21 Jun, 2021
Given a binary string, str and a 2D array Q[][] representing queries of the form {L, R}. In each query, toggle all the characters of the binary strings present in the indices [L, R]. The task is to print the binary string by performing all the queries.
Examples:
Input: str = "101010", Q[][] = { {0, 1}, {2, 5}, {2, 3}, {1, 4}, {0, 5} }
Output: 111000
Explanation:
Query 1: Toggling all the characters of str in the indices [0, 1]. Therefore, str becomes "011010".
Query 2: Toggling all the characters of str in the indices [2, 5]. Therefore, str becomes "010101".
Query 3: Toggling all the characters of str in the indices [2, 3]. Therefore, str becomes "011001".
Query 4: Toggling all the characters of str in the indices [1, 4]. Therefore, str becomes "000111".
Query 5: Toggling all the characters of str in the indices [0, 5]. Therefore, str becomes "111000".
Therefore, the required binary string is "111000".
Input: str = "00101", Q[][]={ {0, 2}, {2, 3}, {1, 4} }
Output: 10000
Naive Approach: The simplest approach to solve the problem is to traverse all the queries arrays and toggle all the characters in the indices [L, R]. Finally, print the binary string.
Time Complexity: O(M * N), Where N denotes the length of the binary string.
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach the idea is to use the Prefix Sum array technique. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the binary string by
// performing all the given queries
string toggleQuery(string str, int Q[][2],
int M)
{
// Stores length of the string
int N = str.length();
// prefixCnt[i]: Stores number
// of times str[i] toggled by
// performing all the queries
int prefixCnt[N + 1] = { 0 };
for (int i = 0; i < M; i++) {
// Update prefixCnt[Q[i][0]]
prefixCnt[Q[i][0]] += 1;
// Update prefixCnt[Q[i][1] + 1]
prefixCnt[Q[i][1] + 1] -= 1;
}
// Calculate prefix sum of prefixCnt[i]
for (int i = 1; i <= N; i++) {
prefixCnt[i] += prefixCnt[i - 1];
}
// Traverse prefixCnt[] array
for (int i = 0; i < N; i++) {
// If ith element toggled
// odd number of times
if (prefixCnt[i] % 2) {
// Toggled i-th element
// of binary string
str[i] = '1' - str[i] + '0';
}
}
return str;
}
// Driver Code
int main()
{
string str = "101010";
int Q[][2] = { { 0, 1 }, { 2, 5 },
{ 2, 3 }, { 1, 4 },
{ 0, 5 } };
int M = sizeof(Q) / sizeof(Q[0]);
cout << toggleQuery(str, Q, M);
}
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
// Function to find the binary
// String by performing all the
// given queries
static String toggleQuery(char[] str,
int Q[][], int M)
{
// Stores length of the String
int N = str.length;
// prefixCnt[i]: Stores number
// of times str[i] toggled by
// performing all the queries
int prefixCnt[] = new int[N + 1];
for (int i = 0; i < M; i++)
{
// Update prefixCnt[Q[i][0]]
prefixCnt[Q[i][0]] += 1;
// Update prefixCnt[Q[i][1] + 1]
prefixCnt[Q[i][1] + 1] -= 1;
}
// Calculate prefix sum of
// prefixCnt[i]
for (int i = 1; i <= N; i++)
{
prefixCnt[i] += prefixCnt[i - 1];
}
// Traverse prefixCnt[] array
for (int i = 0; i < N; i++)
{
// If ith element toggled
// odd number of times
if (prefixCnt[i] % 2 == 1)
{
// Toggled i-th element
// of binary String
str[i] = (char)('1' -
str[i] + '0');
}
}
return String.valueOf(str);
}
// Driver Code
public static void main(String[] args)
{
String str = "101010";
int Q[][] = {{0, 1}, {2, 5},
{2, 3}, {1, 4},
{0, 5}};
int M = Q.length;
System.out.print(
toggleQuery(str.toCharArray(),
Q, M));
}
}
// This code is contributed by shikhasingrajput
Python3
# Python3 program to implement
# the above approach
# Function to find the binary by
# performing all the given queries
def toggleQuery(strr, Q, M):
strr = [i for i in strr]
# Stores length of the string
N = len(strr)
# prefixCnt[i]: Stores number
# of times strr[i] toggled by
# performing all the queries
prefixCnt = [0] * (N + 1)
for i in range(M):
# Update prefixCnt[Q[i][0]]
prefixCnt[Q[i][0]] += 1
# Update prefixCnt[Q[i][1] + 1]
prefixCnt[Q[i][1] + 1] -= 1
# Calculate prefix sum of prefixCnt[i]
for i in range(1, N + 1):
prefixCnt[i] += prefixCnt[i - 1]
# Traverse prefixCnt[] array
for i in range(N):
# If ith element toggled
# odd number of times
if (prefixCnt[i] % 2):
# Toggled i-th element
# of binary string
strr[i] = (chr(ord('1') -
ord(strr[i]) +
ord('0')))
return "".join(strr)
# Driver Code
if __name__ == '__main__':
strr = "101010";
Q = [ [ 0, 1 ],[ 2, 5 ],
[ 2, 3 ],[ 1, 4 ],
[ 0, 5 ] ]
M = len(Q)
print(toggleQuery(strr, Q, M))
# This code is contributed by mohit kumar 29
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to find the binary
// String by performing all the
// given queries
static String toggleQuery(char[] str,
int [,]Q ,
int M)
{
// Stores length of the String
int N = str.Length;
// prefixCnt[i]: Stores number
// of times str[i] toggled by
// performing all the queries
int []prefixCnt = new int[N + 1];
for (int i = 0; i < M; i++)
{
// Update prefixCnt[Q[i,0]]
prefixCnt[Q[i, 0]] += 1;
// Update prefixCnt[Q[i,1] + 1]
prefixCnt[Q[i, 1] + 1] -= 1;
}
// Calculate prefix sum of
// prefixCnt[i]
for (int i = 1; i <= N; i++)
{
prefixCnt[i] += prefixCnt[i - 1];
}
// Traverse prefixCnt[] array
for (int i = 0; i < N; i++)
{
// If ith element toggled
// odd number of times
if (prefixCnt[i] % 2 == 1)
{
// Toggled i-th element
// of binary String
str[i] = (char)('1' -
str[i] + '0');
}
}
return String.Join("", str);
}
// Driver Code
public static void Main(String[] args)
{
String str = "101010";
int [,]Q = {{0, 1}, {2, 5},
{2, 3}, {1, 4},
{0, 5}};
int M = Q.GetLength(0);
Console.Write(toggleQuery(str.ToCharArray(),
Q, M));
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// Javascript program to implement
// the above approach
// Function to find the binary
// String by performing all the
// given queries
function toggleQuery(str, Q, M)
{
// Stores length of the String
let N = str.length;
// prefixCnt[i]: Stores number
// of times str[i] toggled by
// performing all the queries
let prefixCnt = new Array(N + 1);
for(let i = 0; i < N + 1; i++)
{
prefixCnt[i] = 0;
}
for (let i = 0; i < M; i++)
{
// Update prefixCnt[Q[i][0]]
prefixCnt[Q[i][0]] += 1;
// Update prefixCnt[Q[i][1] + 1]
prefixCnt[Q[i][1] + 1] -= 1;
}
// Calculate prefix sum of
// prefixCnt[i]
for (let i = 1; i <= N; i++)
{
prefixCnt[i] += prefixCnt[i - 1];
}
// Traverse prefixCnt[] array
for (let i = 0; i < N; i++)
{
// If ith element toggled
// odd number of times
if (prefixCnt[i] % 2 == 1)
{
// Toggled i-th element
// of binary String
str[i] = String.fromCharCode('1'.charCodeAt(0) -
str[i].charCodeAt(0) + '0'.charCodeAt(0));
}
}
return (str).join("");
}
// Driver Code
let str = "101010";
let Q = [[0, 1], [2, 5],
[2, 3], [1, 4],
[0, 5]];
let M = Q.length;
document.write(
toggleQuery(str.split(""),
Q, M));
// This code is contributed by patel2127
</script>
Time Complexity: O(N + |Q|), Where N is the length of binary string.
Auxiliary Space: O(N)
Similar Reads
Count of substrings of a given Binary string with all characters same
Given binary string str containing only 0 and 1, the task is to find the number of sub-strings containing only 1s and 0s respectively, i.e all characters same. Examples: Input: str = â011âOutput: 4Explanation: Three sub-strings are "1", "1", "11" which have only 1 in them, and one substring is there
10 min read
Find i'th Index character in a binary string obtained after n iterations
Given a decimal number m, convert it into a binary string and apply n iterations. In each iteration, 0 becomes "01" and 1 becomes "10". Find the (based on indexing) index character in the string after the nth iteration. Examples: Input : m = 5, n = 2, i = 3Output : 1Input : m = 3, n = 3, i = 6Output
6 min read
Minimum cost of flipping characters required to convert Binary String to 0s only
Given binary string str, and integers A, which denotes the cost of converting consecutive 1s to 0s, and B, which denotes the cost of converting 0s to 1s. The task is to find the minimum cost to reduce the string str to 0s only. Examples: Input: str = â01101110â, A = 5, B = 1Output: 6Explanation:Conv
8 min read
Minimum substring flips required to convert given binary string to another
Given two binary strings A and B, the task is to find the minimum number of times a substring starting from the first character of A needs to be flipped, i.e. convert 1s to 0s and 0s to 1s, to convert A to B. Examples: Input: A = â0010â, B = â1011âOutput; 3Explanation:Step 1: Flip the entire string
7 min read
Flip the String by either swapping given characters or rotating it horizontally for Q queries
Given a string S of length 2N and Q Queries containing three integers T, A, and B each, where queries can be of the following two types: T=1: Swap the Ath and Bth characters in S.(In 1-based indexing)T=2: Swap the first N characters with the last N characters i.e "ABCD" becomes "CDAB" The task is to
15 min read
Minimize insertions required to make all characters of a given string equal
Given a binary string S of length N, the task is to find the minimum number of characters required to be inserted such that all the characters in the string becomes the same based on the condition that: If '1' is inserted into the string, then all the '0's nearest to the inserted '1' is flipped or v
5 min read
Minimum flips to remove any consecutive 3 0s or 1s in given Binary string
Given a binary string S consisting of N characters, the task is to find the minimum number of flips required such that there don't exist three consecutive same characters. Examples: Input: S = "1100011"Output: 1Explanation:Flip the character at index 3 modifies the string S "1101011" that have no th
5 min read
Program to convert given Binary to its equivalent ASCII character string
Given a binary string str, the task is to find its equivalent ASCII (American Standard Code for Information Interchange) character string. Examples: Input: str = "0110000101100010"Output: abExplanation: Dividing str into set of 8 bits as follows: 01100001 = 97, ASCII value of 97 is 'a'.01100010 = 98
9 min read
Find iâth index character in a binary string obtained after n iterations | Set 2
Given a decimal number m, convert it into a binary string and apply n iterations, in each iteration 0 becomes â01â and 1 becomes â10â. Find ith(based indexing) index character in the string after nth iteration.Examples: Input: m = 5 i = 5 n = 3Output: 1ExplanationIn the first case m = 5, i = 5, n =
12 min read
Min flips of continuous characters to make all characters same in a string
Given a string consisting only of 1's and 0's. In one flip we can change any continuous sequence of this string. Find this minimum number of flips so the string consist of same characters only.Examples: Input : 00011110001110Output : 2We need to convert 1's sequenceso string consist of all 0's.Input
8 min read