Find minimum number of steps to reach the end of String
Given a binary string str of length N and an integer K, the task is to find the minimum number of steps required to move from str to str[N – 1] with the following moves:
- From an index i, the only valid moves are i + 1, i + 2 and i + K
- An index i can only be visited if str[i] = ‘1’
Input: str = “101000011”, K = 5
str -> str -> str -> str
Input: str = “1100000100111”, K = 6
There is no possible path.
Input: str = “10101010101111010101”, K = 4
Approach: The idea is to use dynamic programming to solve the problem.
- It is given that for any index i, it is possible to move to an index i+1, i+2 or i+K.
- One of the three possibilities will give the required result that is the minimum number of steps to reach the end.
- Therefore, the dp array is created and is filled in a bottom-up manner.
Below is the implementation of the above approach:
Time Complexity: O(N) where N is the length of the string.