Number of Beautiful Integers in the Range - Problem

You are given positive integers low, high, and k.

A number is beautiful if it meets both of the following conditions:

  • The count of even digits in the number is equal to the count of odd digits.
  • The number is divisible by k.

Return the number of beautiful integers in the range [low, high].

Input & Output

Example 1 — Basic Range
$ Input: low = 10, high = 20, k = 6
Output: 2
💡 Note: Numbers 12 (even=1, odd=1, 12%6=0) and 18 (even=1, odd=1, 18%6=0) are beautiful
Example 2 — Larger k
$ Input: low = 1, high = 10, k = 1
Output: 1
💡 Note: Only number with equal even/odd digits in range [1,10] is none for single digits, but all are divisible by 1
Example 3 — No Valid Numbers
$ Input: low = 5, high = 5, k = 1
Output: 0
💡 Note: Single digit 5 has 0 even and 1 odd digit, so counts are not equal

Constraints

  • 1 ≤ low ≤ high ≤ 109
  • 1 ≤ k ≤ 20

Visualization

Tap to expand
INPUTALGORITHMRESULTRange: [10, 20]Divisor: k = 6Find Beautiful NumbersBeautiful = Equal even/odd digitsAND divisible by k1218others1Digit DP StatesTrack: position, balance, remainder2Build NumbersTry digits 0-9 at each position3Update StatesBalance: even +1, odd -1Remainder: (rem*10+digit) % k4Count Validbalance == 0 AND remainder == 0Count: 2Beautiful Numbers:12, 1812: even=1, odd=1, 12%6=0 ✓18: even=1, odd=1, 18%6=0 ✓Key Insight:Digit DP efficiently counts valid numbers by tracking digit balance and modulo remainder simultaneously, avoiding the need to generate all numbers in the range.TutorialsPoint - Number of Beautiful Integers in the Range | Digit DP with Memoization
Asked in
Google 15 Amazon 8 Microsoft 12 Meta 6
23.4K Views
Medium Frequency
~45 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen