Find The K-th Lucky Number - Problem

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.

Note: Lucky numbers are ordered as: 4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777, ...

Input & Output

Example 1 — Basic Case
$ Input: k = 4
Output: "47"
💡 Note: Lucky numbers in order: 4(1st), 7(2nd), 44(3rd), 47(4th). The 4th lucky number is "47".
Example 2 — Single Digit
$ Input: k = 1
Output: "4"
💡 Note: The very first lucky number is "4".
Example 3 — Larger Number
$ Input: k = 8
Output: "447"
💡 Note: Lucky numbers: 4, 7, 44, 47, 74, 77, 444, 447. The 8th is "447".

Constraints

  • 1 ≤ k ≤ 109

Visualization

Tap to expand
Find The K-th Lucky Number INPUT Lucky Digits: 4 7 Lucky Number Sequence: 4 7 44 47 74 k=1 k=2 k=3 k=4 k=5 77 444 447 474 ... Input: k = 4 ALGORITHM STEPS 1 Binary Mapping Map k to binary: 4 --> 100 2 Add Offset k + offset: 4 + 2 = 6 3 Convert to Binary 6 in binary = 110 4 Replace Digits 0 --> 4, 1 --> 7 (skip first) 110 (skip '1') "10" --> "47" Binary tree traversal 0=left(4), 1=right(7) FINAL RESULT The 4th Lucky Number: "47" Verification: 4 1st 7 2nd 44 3rd 47 4th Output: "47" Key Insight: Lucky numbers form a complete binary tree! Each number can be found by converting (k + 2^n - 1) to binary and mapping: 0 --> '4', 1 --> '7'. Skip the leading 1 bit. Time: O(log k), Space: O(log k) TutorialsPoint - Find The K-th Lucky Number | Optimal Solution (Binary Mapping)
Asked in
Google 15 Microsoft 12
25.0K Views
Medium Frequency
~15 min Avg. Time
890 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