K-th lexicographical string of given length Last Updated : 05 Aug, 2021 Comments Improve Suggest changes Like Article Like Report Given two integers N and K, the task is to find lexicographically Kth string of length N. If the number of possible strings of length N is less than K, print -1.Examples: Input: N = 3, K = 10 Output: "aaj" Explanation: The 10th string in the lexicographical order starting from "aaa" is "aaj".Input: N = 2, K = 1000 Output: -1 Explanation: A total of 26*26 = 676 strings of length 2 are possible. So the output will be -1. Approach: Let us assume a string of length N as an integer of base 26. For example, if N = 3, the first string will be s = "aaa" whose base 26 representation in integer will be 0 0 0, the second string will be s = "aab" and base 26 representation will be 0 0 1 and so on. Hence each digit can have a value within [0, 25]. Starting from the last digit, we need to change it to all possible values followed by the penultimate digit and so on. So, the simplified problem is to find the representation of a decimal number K into a 26 base number. You can read this post to have a clear idea how to do this. After we find the answer in the form of an integer of base 26, we will convert each digit into its equivalent character, where 0 is 'a', 1 is 'b', .... 24 is 'y', 25 is 'z'. Below is the implementation of the above approach: C++ // C++ program to find the K-th // lexicographical string of length N #include <bits/stdc++.h> using namespace std; string find_kth_String_of_n(int n, int k) { // Initialize the array to store // the base 26 representation of // K with all zeroes, that is, // the initial String consists // of N a's int d[n] = {0}; // Start filling all the // N slots for the base 26 // representation of K for(int i = n - 1; i > -1; i--) { // Store the remainder d[i] = k % 26; // Reduce K k /= 26; } // If K is greater than the // possible number of strings // that can be represented by // a string of length N if (k > 0) return "-1"; string s = ""; // Store the Kth lexicographical // string for(int i = 0; i < n; i++) s += (d[i] + ('a')); return s; } // Driver Code int main() { int n = 3; int k = 10; // Reducing k value by 1 because // our stored value starts from 0 k -= 1; cout << find_kth_String_of_n(n, k); return 0; } // This code is contributed by 29AjayKumar Java // Java program to find the // K-th lexicographical String // of length N class GFG{ static String find_kth_String_of_n(int n, int k) { // Initialize the array to // store the base 26 // representation of K // with all zeroes, that is, // the initial String consists // of N a's int[] d = new int[n]; // Start filling all the // N slots for the base 26 // representation of K for (int i = n - 1; i > -1; i--) { // Store the remainder d[i] = k % 26; // Reduce K k /= 26; } // If K is greater than the // possible number of Strings // that can be represented by // a String of length N if (k > 0) return "-1"; String s = ""; // Store the Kth lexicographical // String for (int i = 0; i < n; i++) s += (char)(d[i] + ('a')); return s; } public static void main(String[] args) { int n = 3; int k = 10; // Reducing k value by 1 because // our stored value starts from 0 k -= 1; System.out.println(find_kth_String_of_n(n, k)); } } // This code is contributed by PrinciRaj1992 Python3 # Python program to find the # K-th lexicographical string # of length N def find_kth_string_of_n(n, k): # Initialize the array to # store the base 26 # representation of K # with all zeroes, that is, # the initial string consists # of N a's d =[0 for i in range(n)] # Start filling all the # N slots for the base 26 # representation of K for i in range(n - 1, -1, -1): # Store the remainder d[i]= k % 26 # Reduce K k//= 26 # If K is greater than the # possible number of strings # that can be represented by # a string of length N if k>0: return -1 s ="" # Store the Kth lexicographical # string for i in range(n): s+= chr(d[i]+ord('a')) return s n = 3 k = 10 # Reducing k value by 1 because # our stored value starts from 0 k-= 1 print(find_kth_string_of_n(n, k)) C# // C# program to find the // K-th lexicographical String // of length N using System; class GFG{ static String find_kth_String_of_n(int n, int k) { // Initialize the array to // store the base 26 // representation of K // with all zeroes, that is, // the initial String consists // of N a's int[] d = new int[n]; // Start filling all the // N slots for the base 26 // representation of K for (int i = n - 1; i > -1; i--) { // Store the remainder d[i] = k % 26; // Reduce K k /= 26; } // If K is greater than the // possible number of Strings // that can be represented by // a String of length N if (k > 0) return "-1"; string s = ""; // Store the Kth lexicographical // String for (int i = 0; i < n; i++) s += (char)(d[i] + ('a')); return s; } // Driver Code public static void Main() { int n = 3; int k = 10; // Reducing k value by 1 because // our stored value starts from 0 k -= 1; Console.Write(find_kth_String_of_n(n, k)); } } // This code is contributed by Code_Mech JavaScript <script> // Javascript program to find the // K-th lexicographical String // of length N function find_kth_String_of_n(n, k) { // Initialize the array to // store the base 26 // representation of K // with all zeroes, that is, // the initial String consists // of N a's let d = new Array(n); d.fill(0); // Start filling all the // N slots for the base 26 // representation of K for (let i = n - 1; i > -1; i--) { // Store the remainder d[i] = k % 26; // Reduce K k = parseInt(k / 26, 10); } // If K is greater than the // possible number of Strings // that can be represented by // a String of length N if (k > 0) return "-1"; let s = ""; // Store the Kth lexicographical // String for (let i = 0; i < n; i++) s += String.fromCharCode(d[i] + ('a').charCodeAt()); return s; } let n = 3; let k = 10; // Reducing k value by 1 because // our stored value starts from 0 k -= 1; document.write(find_kth_String_of_n(n, k)); // This code is contributed by mukesh07. </script> Output: aaj Time Complexity: O(N)Auxiliary Space: O(N) Comment More infoAdvertise with us Next Article K-th lexicographical string of given length P pedastrian Follow Improve Article Tags : Strings Algorithms Mathematical Python DSA lexicographic-ordering +2 More Practice Tags : AlgorithmsMathematicalpythonStrings Similar Reads Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio 10 min read DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on 7 min read Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth 15+ min read Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s 12 min read Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge 14 min read Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir 8 min read Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st 2 min read Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta 15+ min read Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p 11 min read Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read Like