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) < 0, then
    • 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 <= x and k < n, then
      • 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) < 0:
      return 0
   return factorial(x+y) / factorial(x) / factorial(y)

def solve(x, y, k):
   res = []
   p, q = 0, 0
   while (p, q) != (x, y):
      n = paths(x - p - 1, y - q)
      if p + 1 <= x and k < n:
         res.append('H')
         p += 1
      else:
         k -= n
         res.append('V')
         q += 1
   return ''.join(res)

(x, y) = (3, 3)
k = 3
print(solve(x, y, k))

Input

(3, 3), 3

Output

HHVVVH

Updated on: 25-Oct-2021

131 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements