From 1ac61b1a2143855ca4885871db4dbd0dcd548cc3 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 22 Sep 2024 22:14:01 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB440.=20K-th=20Smallest=20in?= =?UTF-8?q?=20Lexicographical=20Order=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...-th-smallest-in-lexicographical-order.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 java/k-th-smallest-in-lexicographical-order.java diff --git a/java/k-th-smallest-in-lexicographical-order.java b/java/k-th-smallest-in-lexicographical-order.java new file mode 100644 index 0000000..97431e4 --- /dev/null +++ b/java/k-th-smallest-in-lexicographical-order.java @@ -0,0 +1,31 @@ +class Solution { + private int distance(int upperBound, long left, long right) { + var dist = 0; + + for (; left <= upperBound; left *= 10, right *= 10) { + dist += Math.min(upperBound + 1, right) - left; + } + + return dist; + } + + public int findKthNumber(int n, int k) { + var current = 1; + --k; + + while (k > 0) { + var d = distance(n, current, current + 1); + + if (d <= k) { + // skipping d numbers at once + ++current; + k -= d; + } else { + current *= 10; + --k; + } + } + + return current; + } +}