- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Program to find lexicographically smallest lowercase string of length k and distance n in Python
- Program to find lexicographically smallest non-palindromic string in Python
- Program to find Lexicographically Smallest String With One Swap in Python
- Program to find lexicographically smallest string after applying operations in Python
- Program to find lexicographically smallest string to move from start to destination in Python
- Program to find lexicographically smallest subsequence of size k in Python
- Program to find kth smallest element in linear time in Python
- Lexicographically Smallest Equivalent String in C++
- Find the lexicographically smallest string which satisfies the given condition in Python
- Program to find the kth smallest element in a Binary Search Tree in Python
- C++ Program to find kth Smallest Element by the Method of Partitioning the Array\n
- Kth Smallest Element in a BST in Python
- Queries to answer the X-th smallest sub-string lexicographically in C++
- Kth Smallest Element in a Sorted Matrix in Python
- Program to find smallest string with a given numeric value in Python

Advertisements