Modify a Binary String by flipping characters such that any pair of indices consisting of 1s are neither co-prime nor divisible by each other
Given an integer N and a binary string consisting of 4*N number of 0s initially, the task is to flip the characters such that any two pair of indices of the string consisting of 1s are neither co-prime nor the pair of indices can be divisible by each other.
Note: Consider 1-based indexing.
Examples:
Input: N = 3, S = “000000000000”
Output: 000000010101
Explanation: In the modified string “000000010101”, the indices of 1s are {8, 10, 12}. In the above set of indices, there does not exist any pair of indices that are co-prime and divisible by each other.
Input: N = 2, S = “00000000”
Output: 00000101
Approach: The given problem can be solved based on the observation that if the characters are flipped at the positions 4*N, 4*N – 2, 4*N – 4, … up to N terms, then there doesn’t exist any pair of indices that are divisible by each other and having GCD as 1.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void findString( char S[], int N)
{
int strLen = 4 * N;
for ( int i = 1; i <= N; i++) {
S[strLen - 1] = '1' ;
strLen -= 2;
}
for ( int i = 0; i < 4 * N; i++) {
cout << S[i];
}
}
int main()
{
int N = 2;
char S[4 * N];
for ( int i = 0; i < 4 * N; i++)
S[i] = '0' ;
findString(S, N);
return 0;
}
|
Java
import java.io.*;
class GFG {
public static void findString( char S[], int N)
{
int strLen = 4 * N;
for ( int i = 1 ; i <= N; i++) {
S[strLen - 1 ] = '1' ;
strLen -= 2 ;
}
System.out.println(S);
}
public static void main(String[] args)
{
int N = 2 ;
char S[] = new char [ 4 * N];
for ( int i = 0 ; i < 4 * N; i++)
S[i] = '0' ;
findString(S, N);
}
}
|
Python3
def findString(S, N) :
strLen = 4 * N
for i in range ( 1 , N + 1 ):
S[strLen - 1 ] = '1'
strLen - = 2
for i in range ( 4 * N):
print (S[i], end = "")
N = 2
S = [ 0 ] * ( 4 * N)
for i in range ( 4 * N):
S[i] = '0'
findString(S, N)
|
C#
using System;
public class GFG
{
public static void findString( char [] S, int N)
{
int strLen = 4 * N;
for ( int i = 1; i <= N; i++) {
S[strLen - 1] = '1' ;
strLen -= 2;
}
Console.WriteLine(S);
}
public static void Main(String[] args)
{
int N = 2;
char [] S = new char [4 * N];
for ( int i = 0; i < 4 * N; i++)
S[i] = '0' ;
findString(S, N);
}
}
|
Javascript
<script>
function findString(S, N) {
var strLen = 4 * N;
for ( var i = 1; i <= N; i++)
{
S[strLen - 1] = "1" ;
strLen -= 2;
}
for ( var i = 0; i < 4 * N; i++)
{
document.write(S[i]);
}
}
var N = 2;
var S = [...Array(4 * N)];
for ( var i = 0; i < 4 * N; i++) S[i] = "0" ;
findString(S, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
31 May, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...