<p>The set <code>[1, 2, 3, ...,&nbsp;n]</code> contains a total of <code>n!</code> unique permutations.</p>

<p>By listing and labeling all of the permutations in order, we get the following sequence for <code>n = 3</code>:</p>

<ol>
	<li><code>&quot;123&quot;</code></li>
	<li><code>&quot;132&quot;</code></li>
	<li><code>&quot;213&quot;</code></li>
	<li><code>&quot;231&quot;</code></li>
	<li><code>&quot;312&quot;</code></li>
	<li><code>&quot;321&quot;</code></li>
</ol>

<p>Given <code>n</code> and <code>k</code>, return the <code>k<sup>th</sup></code> permutation sequence.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 3
<strong>Output:</strong> "213"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 4, k = 9
<strong>Output:</strong> "2314"
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 1
<strong>Output:</strong> "123"
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 9</code></li>
	<li><code>1 &lt;= k &lt;= n!</code></li>
</ul>

import numpy as np
class Solution:

    def factorial(self, n):
        if n == 0 or n == 1:
            return 1
        return self.factorial(n-1) * n

    def getPermutation(self, n: int, k: int, pref_add = 0) -> str:
        if k == 1 or k==0:
            result = ''
            for i in range(1, n+1):
                result += f'{i+pref_add}'
            return result
        if k == self.factorial(n):
            result = ''
            for i in range(1, n+1):
                result = f'{i+pref_add}' + result
            return result
        
        for i in range(1, n):
            if self.factorial(i)>= k:
                prefix = '' 
                for j in range(1, n-i+1):
                    prefix += f'{j+pref_add}'
                return prefix + self.getPermutation(i, k, pref_add=pref_add+n-i)
        
        if self.factorial(n) >= k and self.factorial(n-1) < k:
            m = int(np.ceil(k/self.factorial(n-1)))
            # print(m)
            first_letter = f'{m + pref_add}'
            suffix = self.getPermutation(n - 1, k - self.factorial(n-1)*(m-1), pref_add=pref_add)
            suffix_changed = ''
            for char in suffix:
                if int(char) >= m+pref_add:
                    suffix_changed += f'{int(char) + 1}'
                else:
                    suffix_changed += char
            return first_letter + suffix_changed
28500