Find i’th index character in a binary string obtained after n iterations | Set 2
Last Updated :
29 Nov, 2023
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 = 3
Output: 1
Explanation
In the first case m = 5, i = 5, n = 3.
Initially, the string is 101 ( binary equivalent of 5 )
After 1st iteration - 100110
After 2nd iteration - 100101101001
After 3rd iteration - 100101100110100110010110
The character at index 5 is 1, so 1 is the answer
Input: m = 11 i = 6 n = 4
Output: 1
A naive approach to this problem has been discussed in the previous post.
Efficient algorithm: The first step will be to find which block the i-th character will be after N iterations are performed. In the n'th iteration distance between any two consecutive characters initially will always be equal to 2^n. For a general number m, the number of blocks will be ceil(log m). If M was 3, the string gets divided into 3 blocks. Find the block number in which kth character will lie by k / (2^n), where n is the number of iterations. Consider m=5, then the binary representation is 101. Then the distance between any 2 consecutive marked characters in any i'th iteration will be as follows
0th iteration: 101, distance = 0
1st iteration: 10 01 1 0, distance = 2
2nd iteration: 1001 0110 1001, distance = 4
3rd iteration: 10010110 01101001 10010110, distance = 8
In the example k = 5 and n = 3, so Block_number, when k is 5, will be 0, as 5 / (2^3) = 0
Initially, block numbers will be
Original String : 1 0 1
Block_number : 0 1 2
There is no need to generate the entire string, only computing in the block in which the i-th character is present will give the answer. Let this character be root root = s[Block_number], where s is the binary representation of "m". Now in the final string, find the distance of the kth character from the block number, call this distance as remaining. So remaining = k % (2^n) will be the index of i-th character in the block. If remaining is 0, the root will be the answer. Now, in order to check whether the root is the actual answer use a boolean variable flip which whether we need to flip our answer or not. Following the below algorithm will give the character at the i-th index.
bool flip = true;
while(remaining > 1){
if( remaining is odd )
flip = !flip
remaining = remaining/2;
}

Below is the implementation of the above approach:
C++
// C++ program to find i’th Index character
// in a binary string obtained after n iterations
#include <bits/stdc++.h>
using namespace std;
// Function to find the i-th character
void KthCharacter(int m, int n, int k)
{
// distance between two consecutive
// elements after N iterations
int distance = pow(2, n);
int Block_number = k / distance;
int remaining = k % distance;
int s[32], x = 0;
// binary representation of M
for (; m > 0; x++) {
s[x] = m % 2;
m = m / 2;
}
// kth digit will be derived from root for sure
int root = s[x - 1 - Block_number];
if (remaining == 0) {
cout << root << endl;
return;
}
// Check whether there is need to
// flip root or not
bool flip = true;
while (remaining > 1) {
if (remaining & 1) {
flip = !flip;
}
remaining = remaining >> 1;
}
if (flip) {
cout << !root << endl;
}
else {
cout << root << endl;
}
}
// Driver Code
int main()
{
int m = 5, k = 5, n = 3;
KthCharacter(m, n, k);
return 0;
}
Java
// Java program to find ith
// Index character in a binary
// string obtained after n iterations
import java.io.*;
class GFG
{
// Function to find
// the i-th character
static void KthCharacter(int m,
int n, int k)
{
// distance between two
// consecutive elements
// after N iterations
int distance = (int)Math.pow(2, n);
int Block_number = k / distance;
int remaining = k % distance;
int s[] = new int[32];
int x = 0;
// binary representation of M
for (; m > 0; x++)
{
s[x] = m % 2;
m = m / 2;
}
// kth digit will be
// derived from root
// for sure
int root = s[x - 1 -
Block_number];
if (remaining == 0)
{
System.out.println(root);
return;
}
// Check whether there is
// need to flip root or not
Boolean flip = true;
while (remaining > 1)
{
if ((remaining & 1) > 0)
{
flip = !flip;
}
remaining = remaining >> 1;
}
if (flip)
{
System.out.println((root > 0)?0:1);
}
else
{
System.out.println(root);
}
}
// Driver Code
public static void main (String[] args)
{
int m = 5, k = 5, n = 3;
KthCharacter(m, n, k);
}
}
// This code is contributed
// by anuj_67.
Python3
# Python3 program to find
# i’th Index character in
# a binary string obtained
# after n iterations
# Function to find
# the i-th character
def KthCharacter(m, n, k):
# distance between two
# consecutive elements
# after N iterations
distance = pow(2, n)
Block_number = int(k / distance)
remaining = k % distance
s = [0] * 32
x = 0
# binary representation of M
while(m > 0) :
s[x] = m % 2
m = int(m / 2)
x += 1
# kth digit will be derived
# from root for sure
root = s[x - 1 - Block_number]
if (remaining == 0):
print(root)
return
# Check whether there
# is need to flip root
# or not
flip = True
while (remaining > 1):
if (remaining & 1):
flip = not(flip)
remaining = remaining >> 1
if (flip) :
print(not(root))
else :
print(root)
# Driver Code
m = 5
k = 5
n = 3
KthCharacter(m, n, k)
# This code is contributed
# by smita
C#
// C# program to find ith
// Index character in a
// binary string obtained
// after n iterations
using System;
class GFG
{
// Function to find
// the i-th character
static void KthCharacter(int m,
int n,
int k)
{
// distance between two
// consecutive elements
// after N iterations
int distance = (int)Math.Pow(2, n);
int Block_number = k / distance;
int remaining = k % distance;
int []s = new int[32];
int x = 0;
// binary representation of M
for (; m > 0; x++)
{
s[x] = m % 2;
m = m / 2;
}
// kth digit will be
// derived from root
// for sure
int root = s[x - 1 -
Block_number];
if (remaining == 0)
{
Console.WriteLine(root);
return;
}
// Check whether there is
// need to flip root or not
Boolean flip = true;
while (remaining > 1)
{
if ((remaining & 1) > 0)
{
flip = !flip;
}
remaining = remaining >> 1;
}
if (flip)
{
Console.WriteLine(!(root > 0));
}
else
{
Console.WriteLine(root);
}
}
// Driver Code
public static void Main ()
{
int m = 5, k = 5, n = 3;
KthCharacter(m, n, k);
}
}
// This code is contributed
// by anuj_67.
JavaScript
<script>
// Javascript program to find ith
// Index character in a binary
// string obtained after n iterations
// Function to find
// the i-th character
function KthCharacter(m, n, k)
{
// distance between two
// consecutive elements
// after N iterations
let distance = Math.pow(2, n);
let Block_number = Math.floor(k / distance);
let remaining = k % distance;
let s = new Array(32).fill(0);
let x = 0;
// binary representation of M
for (; m > 0; x++)
{
s[x] = m % 2;
m = Math.floor(m / 2);
}
// kth digit will be
// derived from root
// for sure
let root = s[x - 1 -
Block_number];
if (remaining == 0)
{
document.write(root);
return;
}
// Check whether there is
// need to flip root or not
let flip = true;
while (remaining > 1)
{
if ((remaining & 1) > 0)
{
flip = !flip;
}
remaining = remaining >> 1;
}
if (flip)
{
document.write((root > 0)?0:1);
}
else
{
document.write(root);
}
}
// driver program
let m = 5, k = 5, n = 3;
KthCharacter(m, n, k);
// This code is contributed by susmitakundugoaldanga.
</script>
PHP
<?php
// PHP program to find i’th Index character
// in a binary string obtained after n iterations
// Function to find the i-th character
function KthCharacter($m, $n, $k)
{
// distance between two consecutive
// elements after N iterations
$distance = pow(2, $n);
$Block_number = intval($k / $distance);
$remaining = $k % $distance;
$s = array(32);
$x = 0;
// binary representation of M
for (; $m > 0; $x++)
{
$s[$x] = $m % 2;
$m = intval($m / 2);
}
// kth digit will be derived from
// root for sure
$root = $s[$x - 1 - $Block_number];
if ($remaining == 0)
{
echo $root . "\n";
return;
}
// Check whether there is need to
// flip root or not
$flip = true;
while ($remaining > 1)
{
if ($remaining & 1)
{
$flip = !$flip;
}
$remaining = $remaining >> 1;
}
if ($flip)
{
echo !$root . "\n";
}
else
{
echo $root . "\n";
}
}
// Driver Code
$m = 5;
$k = 5;
$n = 3;
KthCharacter($m, $n, $k);
// This code is contributed by ita_c
?>
Time Complexity: O(log Z), where Z is the distance between initially consecutive bits after N iterations
Auxiliary Space: O(1)
Approach 2: Bitset Approach
C++
#include <bitset>
#include <iostream>
using namespace std;
// Function to find the i-th character
void KthCharacter(int m, int n, int k)
{
bitset<32> binary(m); // binary representation of M
int distance
= 1 << n; // Distance between two consecutive
// elements after N iterations
int blockNumber = k / distance;
int remaining = k % distance;
int root = binary[n - blockNumber
- 1]; // Get the kth digit from root
if (remaining == 0) {
cout << root << endl;
return;
}
bool flip = false;
while (remaining > 1) {
flip = !flip;
remaining = remaining >> 1;
}
if (flip) {
cout << !root << endl;
}
else {
cout << root << endl;
}
}
int main()
{
int m = 5, k = 5, n = 3;
KthCharacter(m, n, k);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.BitSet;
public class Gfg {
// Function to find the i-th character
static void KthCharacter(int m, int n, int k) {
BitSet binary = BitSet.valueOf(new long[] { m }); // Binary representation of M
int distance = 1 << n; // Distance between two consecutive elements after N iterations
int blockNumber = k / distance;
int remaining = k % distance;
int root = binary.get(n - blockNumber - 1) ? 1 : 0; // Get the kth digit from root
if (remaining == 0) {
System.out.println(root);
return;
}
boolean flip = false;
while (remaining > 1) {
flip = !flip;
remaining = remaining >> 1;
}
if (flip) {
System.out.println(root == 0 ? 1 : 0);
} else {
System.out.println(root);
}
}
public static void main(String[] args) {
int m = 5, k = 5, n = 3;
KthCharacter(m, n, k);
}
}
// code is contributed by shinjanpatra
Python3
def KthCharacter(m, n, k):
binary = format(m, '0' + str(n) + 'b') # Binary representation of M
distance = 1 << n # Distance between two consecutive elements after N iterations
blockNumber = k // distance
remaining = k % distance
root = int(binary[n - blockNumber - 1]) # Get the kth digit from root
if remaining == 0:
print(root)
return
flip = False
while remaining > 1:
flip = not flip
remaining = remaining >> 1
if flip:
print(int(not root))
else:
print(root)
if __name__ == "__main__":
m = 5
k = 5
n = 3
KthCharacter(m, n, k)
# This code is contributed by shivamgupta310570
C#
using System;
using System.Collections;
class KthCharacterProgram {
// Function to find the i-th character
static void KthCharacter(int m, int n, int k)
{
// Binary representation of M
BitArray binary
= new BitArray(BitConverter.GetBytes(m));
// Distance between two consecutive elements after N
// iterations
int distance = 1 << n;
// Block number calculation
int blockNumber = k / distance;
// Remaining calculation
int remaining = k % distance;
// Get the kth digit from root
int root = binary[n - blockNumber - 1] ? 1 : 0;
if (remaining == 0) {
Console.WriteLine(root);
return;
}
bool flip = false;
while (remaining > 1) {
flip = !flip;
remaining = remaining >> 1;
}
// Output the result based on flipping
Console.WriteLine(flip ? (root ^ 1) : root);
}
static void Main()
{
int m = 5, k = 5, n = 3;
KthCharacter(m, n, k);
}
}
JavaScript
// Function to find the i-th character
function KthCharacter(m, n, k) {
// Convert m to its binary representation
let binary = m.toString(2);
// Calculate the distance between two consecutive elements after N iterations
let distance = 1 << n;
// Calculate the block number and remaining value
let blockNumber = Math.floor(k / distance);
let remaining = k % distance;
// Get the kth digit from the binary representation
let root = binary[n - blockNumber - 1];
if (remaining === 0) {
console.log(root);
return;
}
let flip = false;
while (remaining > 1) {
flip = !flip;
remaining = remaining >> 1;
}
if (flip) {
console.log(root === '0' ? '1' : '0');
} else {
console.log(root);
}
}
// Main function
function main() {
let m = 5, k = 5, n = 3;
KthCharacter(m, n, k);
}
main();
Time Complexity: O(1), since the number of iterations and the size of the bitset (32 in this case) are constant.
Auxiliary Space: O(1), since the bitset size is constant and does not depend on the input values.
Similar Reads
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
Find k-th bit in a binary string created by repeated invert and append operations
You are given an initial string s starting with "0". The string keeps duplicating as follows. Invert of it is appended to it.Examples: Input : k = 2 Output : 1 Initially s = "0". First Iteration : s = s + s' = "01" Second Iteration : s = s + s' = "0110" The digit at index 2 of s is 1. Input : k = 12
8 min read
Most frequent character in a string after replacing all occurrences of X in a Binary String
Given a string S of length N consisting of 1, 0, and X, the task is to print the character ('1' or '0') with the maximum frequency after replacing every occurrence of X as per the following conditions: If the character present adjacently to the left of X is 1, replace X with 1.If the character prese
15+ min read
Find last index of a character in a string
Given a string str and a character x, find last index of x in str. Examples : Input : str = "geeks", x = 'e' Output : 2 Last index of 'e' in "geeks" is: 2 Input : str = "Hello world!", x = 'o' Output : 7 Last index of 'o' is: 7 Recommended PracticeLast index of a character in the stringTry It! Metho
8 min read
Queries to flip characters of a binary string in given range
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,
8 min read
Find the last player to be able to flip a character in a Binary String
Given a binary string S of length N, the task is to find the winner of the game if two players A and B plays optimally as per the following rules: Player A always starts the game.In a player's first turn, he can move to any index (1-based indexing) consisting of '0' and make it '1'.For the subsequen
10 min read
Find Binary string by converting all 01 or 10 to 11 after M iterations
Given a binary string str[] of size N and an integer M. This binary string can be modified by flipping all the 0's to 1 which have exactly one 1 as a neighbour. The task is to find the final state of the binary string after M such iterations.Note: 2?N?103, 1?M?109 Examples: Input: str="01100", M=1Ou
8 min read
Position of leftmost set bit in given binary string where all 1s appear at end
Given a binary string S of length N, such that all 1s appear on the right. The task is to return the index of the first set bit found from the left side else return -1. Examples: Input: s = 00011, N = 5Output: 3Explanation: The first set bit from the left side is at index 3. Input: s = 0000, N = 4Ou
5 min read
Minimum given operations required to convert a given binary string to all 1's
Given a binary number as a string str of length L. The task is to find the minimum number of operations needed so that the number becomes 2L-1, that is a string consisting of only 1's of the length L. In each operation, the number N can be replaced by N xor (N + 1). Examples: Input: str = "10010111"
7 min read
Minimum characters required to be removed to sort binary string in ascending order - Set 2
Given binary string str of size N, the task is to remove the minimum number of characters from the given binary string such that the characters in the remaining string are in sorted order. Examples: Input: str = â1000101âOutput: 2Explanation: Removal of the first two occurrences of â1â modifies the
10 min read