Find The K-th Lucky Number - Problem

Find the K-th Lucky Number

In a mystical world of numbers, 4 and 7 are considered lucky digits. A number is called lucky if it contains only these lucky digits (4 and 7).

Your task is to find the k-th lucky number in ascending order. For example:

  • 1st lucky number: "4"
  • 2nd lucky number: "7"
  • 3rd lucky number: "44"
  • 4th lucky number: "47"
  • 5th lucky number: "74"
  • 6th lucky number: "77"

Goal: Given an integer k, return the k-th lucky number as a string.

Input & Output

example_1.py โ€” Python
$ Input: k = 1
โ€บ Output: "4"
๐Ÿ’ก Note: The 1st lucky number is "4" (the smallest number containing only digits 4 and 7)
example_2.py โ€” Python
$ Input: k = 5
โ€บ Output: "74"
๐Ÿ’ก Note: Lucky numbers in order: 1st="4", 2nd="7", 3rd="44", 4th="47", 5th="74"
example_3.py โ€” Python
$ Input: k = 10
โ€บ Output: "474"
๐Ÿ’ก Note: The 10th lucky number falls in the 3-digit level: "444", "447", "474", "477", "744", "747", "774", "777" where "474" is the 10th overall

Constraints

  • 1 โ‰ค k โ‰ค 109
  • The answer will fit in a 32-bit integer when converted to number
  • Lucky numbers contain only digits 4 and 7

Visualization

Tap to expand
Lucky Number Tree StructureLevel 1 (2^1=2 numbers):4(1st)7(2nd)Level 2 (2^2=4 numbers):44(3rd)47(4th)74(5th)77(6th)Level 3 (2^3=8 numbers):444447474477744747774777Algorithm for k=5:1. Find level: 2^1=2, 2^1+2^2=6 โ†’ k=5 is in level 22. Position in level: 5 - 2 - 1 = 2 (0-indexed)3. Binary representation: 2 = 10โ‚‚4. Map to lucky: 1โ†’7, 0โ†’4 โ†’ "74"
Understanding the Visualization
1
Tree Structure
Level 1 has 2 numbers (4,7), Level 2 has 4 numbers (44,47,74,77), etc.
2
Level Detection
Calculate which level contains the k-th number using powers of 2
3
Position Mapping
Convert the position within level to binary representation
4
Binary to Lucky
Map each binary bit: 0โ†’'4', 1โ†’'7' to construct the result
Key Takeaway
๐ŸŽฏ Key Insight: Lucky numbers form a complete binary tree where each level doubles the count. Using binary representation allows direct computation in O(log k) time.
Asked in
Google 45 Amazon 35 Facebook 28 Microsoft 22
28.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen