AlgoMaster Logo

Numbers At Most N Given Digit Set

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Enumeration

Intuition:

The brute force method involves generating all possible numbers from the given digit set and checking if they are less than or equal to the target number N. This approach is based on generating permutations of increasing lengths and counting how many are valid.

Steps:

  1. Convert the integer N to a string to easily access individual digits.
  2. Generate all numbers of lengths from 1 up to the length of N using the digits.
  3. For each generated number, check if it is less than or equal to N and count it.

Code:

2. Dynamic Programming with Digit DP

Intuition:

This approach leverages digit dynamic programming to count the valid numbers directly instead of generating and validating them one by one. We pre-compute the numbers using dynamic programming, breaking the problem into manageable sub-problems.

Steps:

  1. Define a recursive function with memoization to solve for smaller sub-problems.
  2. Use the DP table to store results of previously computed states.
  3. Accumulate results from the DP table to get the final count of valid numbers.

Code:

3. Mathematical Counting

Intuition:

Instead of generating numbers one-by-one, this approach leverages counting principles. We break down the problem by counting numbers having fewer digits than N and exactly digits of N.

Steps:

  1. Count numbers of all lengths smaller than the length of N.
  2. Use prefix-based digit-by-digit comparison to generate valid numbers of the same length as N.
  3. Accumulate the count based on the above computations.

Code: