Problem Description
Find the k-th lucky number where a lucky number contains only the digits 4 and 7. All lucky numbers are sorted in increasing order. For example, the sequence starts as: 4, 7, 44, 47, 74, 77, 444, ... and so on.
Key Insights
- Lucky numbers consist solely of the digits 4 and 7.
- All lucky numbers with fewer digits are smaller than those with more digits.
- For any given digit length L, there are 2^L lucky numbers.
- The k-th lucky number can be found by first determining its digit length and then using a binary representation mapping (0 maps to 4 and 1 maps to 7) corresponding to its position.
Space and Time Complexity
Time Complexity: O(L) where L is the number of digits in the resulting lucky number (at most ~30). Space Complexity: O(L) for constructing the resulting string.
Solution
To obtain the k-th lucky number:
- Determine the minimum digit length L such that the total count of lucky numbers from lengths 1 to L is at least k.
- Compute the offset (zero-indexed) of k within the set of lucky numbers of length L.
- Convert the offset into a binary string of length L by padding with zeros.
- Replace each binary digit with the corresponding lucky digit ('0' becomes '4' and '1' becomes '7') to form the k-th lucky number.