
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
K-th Smallest in Lexicographical Order in C++
Suppose we have two values n and k. We have to find the lexicographically kth smallest integer in the range of 1 to n. So if the input is like n = 14 and k = 3, then the output will be 11, as the sequence will be [1, 10, 11, 12, 13, 14, 2, 3, 4, 5, 6, 7, 8, 9], then the kth number is 11.
To solve this, we will follow these steps −
- Define a function findKthNumber(), this will take n, k,
- curr := 1
- (decrease k by 1)
- while k is non-zero, do −
- steps := call the function calcSteps(n, curr, curr + 1)
- if steps <= k, then −
- k := k - steps
- (increase curr by 1)
- Otherwise
- curr := curr * 10
- k := k - 1
- return curr
- Define a function calcSteps(), this will take nax, n1, n2,
- ret := 0
- while n1 <= nax, do −
- ret := ret + minimum of nax + 1 and n2 – n1
- n1 := n1 * 10
- n2 := n2 * 10
- return ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; typedef long long int lli; class Solution { public: int findKthNumber(int n, int k) { int curr = 1; k--; while(k){ int steps = calcSteps(n, curr, curr + 1); if(steps <= k){ k -= steps; curr++; }else{ curr *= 10; k -= 1; } } return curr; } int calcSteps(lli nax, lli n1, lli n2){ int ret = 0; while(n1 <= nax){ ret += min(nax + 1, n2) - n1; n1 *= 10; n2 *= 10; } return ret; } }; main(){ Solution ob; cout << (ob.findKthNumber(14,3)); }
Input
14,3
Output
11
- Related Articles
- Find k-th smallest element in BST (Order Statistics in BST) in C++
- K-th Smallest Prime Fraction in C++
- Find K-th Smallest Pair Distance in C++
- The k-th Lexicographical String of All Happy Strings of Length n in C++
- Find k-th smallest element in given n ranges in C++
- Find m-th smallest value in k sorted arrays in C++
- Last Substring in Lexicographical Order in C++
- How to Sort Elements in Lexicographical Order (Dictionary Order) in Golang?
- Sort the words in lexicographical order in Java
- Sort the words in lexicographical order in C#
- Sort the words in lexicographical order in Python
- C++ Program to Sort Elements in Lexicographical Order (Dictionary Order)
- Java Program to Sort Elements in Lexicographical Order (Dictionary Order)
- Swift Program to Sort Elements in Lexicographical Order (Dictionary Order)
- Haskell Program to Sort Elements in Lexicographical Order (Dictionary Order)

Advertisements