Program to find lexicographically smallest string to move from start to destination in Python

Suppose we are at at (0, 0) position in the Cartesian plane. We want to go to the point (x, y) using only horizontal(H) and vertical(V) moves of single unit. There are more than one possible ways to reach destination. Each way comprises of few H moves and few V moves. (For example if we want to go to point (2,2) from point (0,0), then HVVH is one of the possible ways.) If we have another value k, we have to find the lexicographically kth smallest way of going to the destination.

So, if the input is like (x, y) = (3, 3) k = 3, then the output will be "HHVVVH"

To solve this, we will follow these steps −

  • Define a function paths() . This will take x, y
  • if min(x, y)
  • return 0
  • return factorial(x+y)/factorial(x)/factorial(y)
  • From the main method, do the following -
  • res := a new list
  • (p, q) := (0, 0)
  • while (p, q) is not same as (x, y), do
    • n := paths(x - p - 1, y - q)
    • if p + 1
    • insert 'H' at the end of res
    • p := p + 1
  • otherwise,
    • k := k - n
    • insert 'V' at the end of res
    • q := q + 1
  • return characters of res after joining
  • Example

    Let us see the following implementation to get better understanding −

    from math import factorial
    
    def paths(x, y):
       if min(x, y) 

    Input

    (3, 3), 3
    

    Output

    HHVVVH
    Updated on: 2021-10-25T06:47:12+05:30

    282 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements