Problem · Array

Largest Number Below N from Reusable Digits

Learn this problem
MediumByteDance logoByteDanceFULLTIMEPHONE SCREEN

Problem statement

Given a positive integer n and a set of decimal digits digits, construct the largest non-negative integer that is strictly smaller than n and uses only digits from digits.

Each allowed digit may be reused any number of times. A multi-digit result cannot begin with zero, but the one-digit result 0 is valid. Return -1 when no valid result exists.

Function

largestNumberBelow(n: int, digits: int[]) → int

Examples

Example 1

n = 23415digits = [2,4,9]return = 22999

The prefix 23 cannot be continued with an allowed digit below 4, so the construction backtracks to 22 and fills the suffix with 9.

Example 2

n = 100digits = [0,1]return = 11

No valid three-digit answer is below 100, so the best two-digit construction is 11.

Constraints

  • 1 <= n <= 10^9
  • 1 <= digits.length <= 10
  • 0 <= digits[i] <= 9
  • All values in digits are distinct.

More ByteDance problems

drafts saved locally
public int largestNumberBelow(int n, int[] digits) {
    // Write your code here.
}
n23415
digits[2,4,9]
expected22999
checking account