call(back)
Algorithms & Data StructuresmediumSign in to star problems

Largest Number Below a Limit From Allowed Digits

Given a positive integer limit and a set of allowed decimal digits, build the largest integer that is strictly smaller than limit and is written using only allowed digits. Digits may be reused any number of times.

limit is passed as a decimal string (up to 100 digits, no leading zeros). Return the answer as a decimal string, or "-1" when no such number exists. The answer must be written canonically: no leading zeros, except that the number zero is "0".

largestBelow("23415", [2, 4, 9])  ->  "22999"
largestBelow("1000", [9])         ->  "999"
largestBelow("10", [0, 1])        ->  "1"
largestBelow("1", [1])            ->  "-1"

The screen leaves this problem under twenty minutes, so settle the two unspecified points first: leading zeros, and what to return when nothing fits.

Hints

Hint 1

A number with as many digits as limit is smaller exactly when it agrees with limit on some prefix and then has a smaller digit. After that position every digit is free.

Hint 2

The longer the shared prefix, the larger the result. So look for the last position where the prefix before it is made of allowed digits and an allowed digit smaller than the limit's digit exists.

Hint 3

If no position works, the answer has one digit fewer: the largest allowed digit repeated. Zero needs care in both branches.

Topics

Asked at

Similar Problems6