Skip to content

Commit

Permalink
feat(440): Hard
Browse files Browse the repository at this point in the history
Given two integers n and k, return the kth lexicographically smallest integer in the range [1, n].

Example 1:

Input: n = 13, k = 2
Output: 10
Explanation: The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.
Example 2:

Input: n = 1, k = 1
Output: 1

Constraints:

1 <= k <= n <= 109
  • Loading branch information
DziedzicGrzegorz committed Sep 22, 2024
1 parent e4c440c commit b013f7b
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
29 changes: 29 additions & 0 deletions internal/Leetcode/440/440.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package _440

func findKthNumber(n int, k int) int {
current := 1
k -= 1 // ponieważ zaczynamy od pierwszej liczby

for k > 0 {
steps := calculateSteps(current, current+1, n)
if steps <= k {
current += 1
k -= steps
} else {
current *= 10
k -= 1
}
}

return current
}

func calculateSteps(curr, next, n int) int {
steps := 0
for curr <= n {
steps += min(n+1, next) - curr
curr *= 10
next *= 10
}
return steps
}
48 changes: 48 additions & 0 deletions internal/Leetcode/440/440_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package _440

import (
"testing"
)

func Test_findKthNumber(t *testing.T) {
type args struct {
n int
k int
}
tests := []struct {
name string
args args
want int
}{
{
name: "Example 1",
args: args{
n: 13,
k: 2,
},
want: 10,
},
{
name: "Example 2",
args: args{
n: 10,
k: 3,
},
want: 2,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := findKthNumber(tt.args.n, tt.args.k); got != tt.want {
t.Errorf("findKthNumber() = %v, want %v", got, tt.want)
}
})
}
}

func BenchmarkFindKthNumber(b *testing.B) {
for i := 0; i < b.N; i++ {
findKthNumber(4089173, 3098723)
}
}

0 comments on commit b013f7b

Please sign in to comment.