- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
- if c is same as last, then
- return blank string
- From the main method call solve(n, k, Null)
Let us see the following implementation to get better understanding:
Example Code
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
Advertisements