Program to check number of ways we can move k times and return back to first place in python


Suppose we are at position 0 of n length list, and on each step, we can move right one place or left one place (not exceeding bounds), or stay at the same position. Now if we can take exactly k steps, then we have to find how many unique walks we can take and reach back to index 0. If the answer is very large return it mod 10^9 + 7.

So, if the input is like n = 7 k = 4, then the output will be 9, as the actions are- 

  • [Right, Right, Left, Left],
  • [Right, Left, Right, Left],
  • [Stay, Stay, Stay, Stay],
  • [Right, Left, Stay, Stay],
  • [Stay, Stay, Right, Left],
  • [Right, Stay, Stay, Left],
  • [Right, Stay, Left, Stay],
  • [Stay, Right, Left, Stay],
  • [Stay, Right, Stay, Left],

To solve this, we will follow these steps −

  • m := 10^9 + 7
  • N := length
  • Define a function dp() . This will take i, jumps
  • if jumps is same as 0, then
    • return (true when i is same as 0, otherwise false)
  • count := dp(i, jumps - 1)
  • if i >= 0, then
    • count := count + dp(i + 1, jumps - 1)
  • if i <= N - 1, then
    • count := count + dp(i - 1, jumps - 1)
  • return count
  • From the main method do the following:
  • return dp(0, n) mod m

Let us see the following implementation to get better understanding −

Example 

Live Demo

class Solution:
   def solve(self, length, n):
      MOD = 10 ** 9 + 7
      N = length

      def dp(i, jumps):
         if jumps == 0:
            return +(i == 0)

         count = dp(i, jumps - 1)
         if i >= 0:
            count += dp(i + 1, jumps - 1)
         if i <= N - 1:
            count += dp(i - 1, jumps - 1)
         return count
      return dp(0, n) % MOD    
ob = Solution()
n = 7
k = 4
print(ob.solve(n, k))

Input

7, 4

Output

9

Updated on: 02-Dec-2020

63 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements