Find lexicographical permutations
Encoding

I hope I understood the problem correctly :)

When observing the problem, I found you can replace the H and V with 0 and 1. The lexicographical permutations then become binary numbers. There are only 10 V's and 10 H's, so the final number will be below 2^20 so fits even in an int.

   HHHVV -&gt; 00011
   VVHHH -&gt; 11000
   etc.


Start out by setting the starting int to  (1 &lt;&lt; Vs) -1 and use the next-bit permutation logic from here

Then, if you found the nth permutation, transform it back to a String

Time complexity

As calculation the next bit permutation is simply a constant time calculation, finding the nth permutation takes O(n) time.

Proposed solution

public class Permutations
{
    //treat H as 0, V as 1.
    private static String getLongAsHVString( long size, long l )
    {
        String s = Long.toBinaryString( l ).chars().mapToObj( Permutations::getStr ).collect( Collectors.joining() );

        //Prepend the 'missing' zeroes as 'H' s
        while ( s.length() &lt; size )
        {
            s = "H" + s;
        }
        return s;
    }

    private static String getStr( int c )
    {
        return ( c == '0' ) ? "H" : "V";
    }

    private static long getNthLexoPerm( int hCount, int vCount, int n )
    {
        long current = ( 1 &lt;&lt; vCount ) - 1;

        for ( int i = 0; i &lt; n; i++ )
        {
            current = nextPerm( current );
        }
        return current;
    }

    private static String getNthLexoPermAsString( int hCount, int vCount, int n )
    {
        return getLongAsHVString( hCount + vCount, getNthLexoPerm( hCount, vCount, n ) );

    }

    public static long nextPerm( long v )
    {
        long t = ( v | ( v - 1 ) ) + 1;
        return t | ( ( ( ( t &amp; -t ) / ( v &amp; -v ) ) &gt;&gt; 1 ) - 1 );

    }

    public static void main( String[] args )
    {

        System.out.println( getNthLexoPermAsString( 2, 2, 3 ) );
        System.out.println( getNthLexoPermAsString( 4, 5, 4 ) );
    }

}