ronith
11/6/2018 - 11:27 AM

Lexicographically Kth smallest way to reach given coordinate from origin

Given a coordinate (x, y) on a 2D plane. We have to reach (x, y) from the current position which is at origin i.e (0, 0). In each step, we can either move vertically or horizontally on the plane. While moving horizontally each step we write ‘H’ and while moving vertically each step we write ‘V’. So, there can be possibly many strings containing ‘H’ and ‘V’ which represents a path from (0, 0) to (x, y). The task is to find the lexicographically Kth smallest string among all the possible strings.

Examples: Input: x = 2, y = 2, k = 2 Output: HVVH Explanation: There are 6 ways to reach (2, 2) from (0, 0). The possible list of strings in lexicographically sorted order: [“HHVV”, “HVHV”, “HVVH”, “VHHV”, “VHVH”, “VVHH”]. Hence, the lexicographically 2nd smallest string is HVHV. Input : x = 2, y = 2, k = 3 Output : VHHV

Approach: The idea is to use recursion to solve the problem. Number of ways to reach (x, y) from origin is x + yCx. Now observe, the number of ways to reach (x, y) from (1, 0) will be (x + y – 1, x – 1) because we have already made a step in the horizontal direction, so 1 is subtracted from x. Also, the number of ways to reach (x, y) from (0, 1) will be (x + y – 1, y – 1) because we have already made a step in the vertical direction, so 1 is subtracted from y. Since ‘H’ is lexicographically smaller than ‘V’, so among all stringsa starting strings will contains ‘H’ in the beginning i.e inital movements will be Horizontal. So, if K <= x + y – 1Cx – 1, we will take ‘H’ as first step else we will take ‘V’ as first step and solve for number of goings to (x, y) from(1, 0) will be K = K – x + y – 1Cx – 1.

//https://www.geeksforgeeks.org/lexicographically-kth-smallest-way-reach-given-coordinate-origin/
#include <bits/stdc++.h>
using namespace std;

long fact (vector <long> dp, int a, int b) {
    return dp[a+b]/ (dp[a]*dp[b]);
}

void func(vector <long> dp, int x, int y, int k) {
    if (x== 0&&y==0)
        return;
    else if (x==0) {
        cout<< 'V';
        func(dp,x,y-1,k);
    }
    else if (y== 0) {
        cout<< 'H';
        func(dp,x-1,y,k);
    }
    else {
        int num= fact(dp, x-1,y);
        if (k<num) {
            cout<< 'H';
            func(dp,x-1,y,k);
        }
        else {
            cout<< 'V';
            func(dp,x,y-1,k-num);
        }
    }
}

int main() {
    int x=2, y=2, k;
    vector <long> dp(x+y+1, -1);
    dp[0]= 1;
    for (int i=1;i<=x+y; i++)
        dp[i]= i*dp[i-1];
    for (k=0;k<6;k++) {
        func (dp, x,y,k);
        cout<<endl;
    }
}