Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
- n := paths(x - p - 1, y - q)
- if p + 1
- insert 'H' at the end of res
- p := p + 1
- k := k - n
- insert 'V' at the end of res
- q := q + 1
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), 3Output
HHVVVH
Advertisements
