I am pretty sure this problem is from one of the contests - Hackwithinfy and Infytq. It was one of the problems my friend had to solve. We later thought of upsolving it. I tried finding a pattern in the output - Wrote a brute-force solution and generated answers for smaller values of N. Luckily, I found the pattern on OEIS.
Here’s how it worked.
The sequence available on OEIS:
What you would like to stress more is this part: (The recurrence relation)
a(2n) = 3\times a(n),\ a(2n+1) = 2\times a(n+1)+a(n), with\ a(1) = 1.
The implementation.
Python Code
import sys
sys.setrecursionlimit(10**6)
map = dict()
mod = 10**9 + 7
def solve(N):
if N in map:
return map[N]
elif N == 0:
return 0
elif N == 1:
return 1
elif N % 2 == 0:
ans = solve(N // 2)
map[N] = (ans * 3) % mod
return map[N]
else:
ans = 2 * solve(N // 2) + solve(N // 2 + 1)
map[N] = ans % mod
return map[N]
def main():
N = int(input(), 2) + 1
print(solve(N) % mod)
main()
This is a DP approach. Unfortunately, this approach was giving Segmentation fault in local machine for strings of length 10^6. Though it was still working fine with strings of length 10^5. The worst-case time it had taken to run against inputs of length 10^5 was around 1-2 seconds though.
Maybe, @cubefreak777 can help us with more optimal approach.





