Program to find kth smallest n length lexicographically smallest string in python


Suppose we have a number n and another value k. Now let us consider a string containing only "0", "1", and "2"s where no character is repeated in succession. We have to select such strings of length n and find the kth lexicographically smallest string. If there is no kth string, return empty string.

So, if the input is like n = 4 k = 2, then the output will be "0120".

To solve this, we will follow these steps:

  • define a method solve() this will take s, k and last
  • if s is same as 0, then
    • return blank string
  • for each character c in "012", do
    • if c is same as last, then
      • go for next iteration
    • if k < 2^(s-1), then
      • return c + solve(s - 1, k, c)
    • k := k - 2^(s-1)
  • return blank string
  • From the main method call solve(n, k, Null)

Let us see the following implementation to get better understanding:

Example Code

Live Demo

class Solution:
   def solve(self, s, k, last=None):
      if s == 0:
         return ""
         for c in "012":
            if c == last:
               continue
            if k < 2 ** (s - 1):
               return c + self.solve(s - 1, k, c)
            k -= 2 ** (s - 1)
         return ""

ob = Solution()
n = 4
k = 2
print(ob.solve(n, k))

Input

4, 2

Output

0120

Updated on: 25-Nov-2020

365 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements