From 1329d518f1c30c5093fec173ca9efb09cd8f82ab Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Sun, 22 Sep 2024 23:08:58 +0530 Subject: [PATCH] Create 440. K-th Smallest in Lexicographical Order1 --- 440. K-th Smallest in Lexicographical Order1 | 28 ++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 440. K-th Smallest in Lexicographical Order1 diff --git a/440. K-th Smallest in Lexicographical Order1 b/440. K-th Smallest in Lexicographical Order1 new file mode 100644 index 0000000..0440b5c --- /dev/null +++ b/440. K-th Smallest in Lexicographical Order1 @@ -0,0 +1,28 @@ +class Solution { +public: + long countSteps(long prefix, long n) { + long steps = 0, nextPrefix = prefix + 1; + while (prefix <= n) { + steps += min(n + 1, nextPrefix) - prefix; + prefix *= 10; + nextPrefix *= 10; + } + return steps; + } + + int findKthNumber(int n, int k) { + int curr = 1; + k--; + while (k > 0) { + long steps = countSteps(curr, n); + if (steps <= k) { + curr++; + k -= steps; + } else { + curr *= 10; + k--; + } + } + return curr; + } +};