Find the kth eleven-non-free number

前端 未结 8 2125
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-04 10:10

Let\'s define eleven-non-free numbers:

If we consider a number as a string, then if any substring inside is a (non-zero) power of 11, then this

8条回答
  •  北恋
    北恋 (楼主)
    2021-02-04 10:39

    It's interesting how easily people get scared by the term "brute force" without even trying to quantify it :)

    Brute force solution is actually O(R * log R)

    where R is the result (k-th eleven-non-free number). You just test all numbers 1..R and for each of them you perform string searches for 11, 121, 1331, 14641 etc. using prepared automaton (for given number of digits). O(R * log R) doesn't look that bad, if you look at it this way, does it? :-)

    Generation solution?

    Clever idea is to try to generate the number more directly:

    1. either by generating directly the k-th number;
    2. or by sequentially generating all 1-k eleven-non-free numbers;
    3. or by generating all eleven-non-free numbers < 10^n at once and sort them up.

    Solution 1 would have to be very clever, if not close to impossible. Solution 2 seems better than brute force solution because it skips those numbers which are not eleven-non-free. Solution 3 would be an easily implemented alternative, which brings us to important question:

    How many eleven-non-free numbers < 10n exist?

    Easy combinatorics (works exactly for n <= 10; for higher n it is close approximation, neglecting that 112 is substring of 1113 and 11 is substring of 1111 and 1119):

    enter image description here

    so basicly for the limit 10n you get more than 10n-2 solutions! This means that number of solutions is a constant proportion of the limit, which means that

    O(R) = O(k)

    which implies that

    The brute force solution is actually O(k * log k), as well as the generate-all solution!

    The dreaded brute force solution kooks much much better now, doesn't it? Yet it's still the same :)

    Can we get better than this?

    • Solution 1 - would be a chance, but close to magic.
    • Solution 2 - the best you can hope for is O(k) but you would have to be very careful to achieve this. There will be many complications that will make it uneasy to select next smallest eleven-non-free-number. E.g. when generating all 11xxx, 121xx, 1331x, eg. 13121 falls in between, making any automatic generation of ordered numbers difficult, let alone duplicities caused by pattern appearing in xxx digits etc. You will probably end up with some complicated data structure that will force O(log k) in each step, and thus O(k log k) in total.
    • Solution 3 - this we already know is O(k log k), which is the same as to find k-th number.

提交回复
热议问题