Find The K-th Lucky Number Problem
Description
LeetCode Problem 2802.
We know that 4 and 7 are lucky digits. Also, a number is called lucky if it contains only lucky digits.
You are given an integer k, return the k^th lucky number represented as a string.
Example 1:
Input: k = 4
Output: "47"
Explanation: The first lucky number is 4, the second one is 7, the third one is 44 and the fourth one is 47.
Example 2:
Input: k = 10
Output: "477"
Explanation: Here are lucky numbers sorted in increasing order:
4, 7, 44, 47, 74, 77, 444, 447, 474, 477. So the 10^th lucky number is 477.
Example 3:
Input: k = 1000
Output: "777747447"
Explanation: It can be shown that the 1000^th lucky number is 777747447.
Constraints:
1 <= k <= 10^9
Solution
Approach: Mathematics
There are 2^n lucky numbers with exactly n digits, since each digit is 4 or 7. Start with n = 1 and, while k > 2^n, subtract 2^n from k and increase n. When the loop stops, the answer has n digits and is the k-th one among them, in sorted order.
Now fix the digits from left to right. For each position, the numbers that start with 4 come first and there are 2^(n-1) of them (counting the remaining positions). If k is at most that many, put 4; otherwise put 7 and subtract that count from k. Repeat for the remaining positions.
Complexity: Time O(log k), space O(log k).
class Solution:
def kthLuckyNumber(self, k: int) -> str:
n = 1
while k > 1 << n:
k -= 1 << n
n += 1
ans = []
while n:
n -= 1
if k <= 1 << n:
ans.append("4")
else:
ans.append("7")
k -= 1 << n
return "".join(ans)