Find the Kth Lucky Number

Asked atMicrosoft
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The 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 kth lucky number represented as a string.

Input : k = 3 Output : "44" Explanation : The first lucky number is 4, the second one is 7and the third lucky number is 44.

Input : k = 1000 Output : "777747447" Explanation : It can be shown that the 1000th lucky number is 777747447.

**Input : **k = 15

  • 1 <= k <= 109

cpp

class Solution {
    public:
        string kthLuckyNumber(int k) {
            //your code goes here
        }
};

java

class Solution {
    public String kthLuckyNumber(int k) {
        //your code goes here
    }
}

python

class Solution:
    def kthLuckyNumber(self, k: int) -> str:
        #your code goes here

javascript

class Solution {
    kthLuckyNumber(k) {
        //your code goes here
    }
}

csharp

class Solution
{
    public string KthLuckyNumber(int k)
    {
        //your code goes here
    }
}

go

func kthLuckyNumber(k int) string {

}
Stuck? Show a way to structure it+
  1. 01Count how many strings each length contributes
  2. 02Locate the length containing k
  3. 03Convert the within-level index to exactly L bits
  4. 04Map bits to digits and return

Reference answer

Then expect these follow-ups

  • What is the kth number using digits 0, 1, and 2?

    Tests: follow-up reasoning

  • Can you derive the answer without enumerating strings?

    Tests: follow-up reasoning

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question