03. Trail of ones
The problem can be found at the following link: Question Link
My Approach
Initialize
modto (10^9 + 7) to handle large numbers and prevent overflow.Initialize
outto 1, which will store the number of valid sequences of ones.Initialize
xto 0 andyto 1, representing the number of valid sequences ending in a single one or two consecutive ones respectively.Iterate from 3 to
n:Update
outto(out * 2 + x + y) % modto include new sequences formed by appending "0" or "1" to previous valid sequences.Temporarily store the current value of
xinz.Update
xto the current value ofy.Update
yto(x + z) % mod, maintaining the count of sequences ending in two consecutive ones.
Return the final value of
out.
Time and Auxiliary Space Complexity
Time Complexity:
(O(n)), since we iterate from 3 ton.Auxiliary Space Complexity:
(O(1)), as we use a constant amount of extra space regardless of the input size.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.
Last updated
Was this helpful?