# Modify binary array and return kth element

Hello All,
I am struggling to optimize solution of a problem.
Problem statement is:
method has 3 input parameters
a. Binary arraylist like [0,1,0,0,1]
b. An integer m
c. An integer k
You have to do iteration from 1 to m and in each iteration modify binary array with following rule
a. If there is 0 at index i i.e. list.get(i)==0 then replace it with 0,1
b. If there is 1 at index i i.e. list.get(i)==1 then replace it with 1,0
After iteration finishes, return the element in the arraylist at index k i.e. list.get(k), from the method.
Example if input arraylist is [0,1,0] and m=2 and k=7
Then after first iteration arraylist will be [0,1,1,0,0,1]
After second iteration arraylist will be [0,1,1,0,1,0,0,1,0,1,1,0]
After m iteration finishes, kth element is 0 i.e value at list.get(k) is 0, so return 0 from the method.

@hearvishwas Here is your solution. I’m busy now, if you need clarification, just let me know, I’ll try my best to explain it.
You should check out this changing format:

``````0        1        0
01       10       01
0110     1001     0110
01101001 10010110 01101001
``````
Solution Code
``````#include <bits/stdc++.h>
using namespace std;

void solve() {
int n, m, k;
string s, b;
cin >> s >> m >> k;
n = 1 << m;  // 2^m
int p = (float(k) / float(n)) + .9;
b.push_back(s[p - 1]);
for (int i = 1; i <= m; i++) {
string a;
for (auto ch : b) a.push_back((1 - (ch - '0')) + '0');
b.append(a);
}
int pos = k - ((p - 1) * n);
cout << b[pos - 1] << '\n';
}

int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
solve();
return 0;
}
``````
``````//Example input:
010
2 11
//output
1
// if k = 7, output 0
// if k = 12, output 0...and so on
``````