Numbers With Repeated Digits - Problem

Given an integer n, return the number of positive integers in the range [1, n] that have at least one repeated digit.

For example, if n = 100, numbers like 11, 22, 33, 44, 55, 66, 77, 88, 99, 100 all have repeated digits.

Input & Output

Example 1 — Small Number
$ Input: n = 20
Output: 1
💡 Note: Only number 11 has repeated digits in range [1, 20]
Example 2 — Medium Number
$ Input: n = 100
Output: 10
💡 Note: Numbers 11, 22, 33, 44, 55, 66, 77, 88, 99, 100 all have repeated digits
Example 3 — Single Digit
$ Input: n = 5
Output: 0
💡 Note: Numbers 1, 2, 3, 4, 5 all have unique digits (single digit numbers)

Constraints

  • 1 ≤ n ≤ 109

Visualization

Tap to expand
Numbers With Repeated Digits INPUT Range [1, n] where n = 20 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Repeated digit n = 20 Find repeated digits in [1,20] ALGORITHM STEPS 1 Count All Numbers Total numbers = n = 20 2 Digit DP Approach Count numbers with ALL unique digits using DP 3 Count Unique Digits 1-digit: 9 (1-9) 2-digit: 10,12-20 = 10 Total unique = 19 4 Subtract repeated = n - unique = 20 - 19 = 1 Result = n - countUnique(n) = 20 - 19 = 1 FINAL RESULT Numbers with repeated digits: 11 digit 1 repeats Breakdown: Total numbers: 20 Unique digit numbers: 19 Repeated digit numbers: 1 OUTPUT 1 OK - Verified Key Insight: Instead of counting numbers WITH repeated digits directly (harder), we count numbers with ALL UNIQUE digits using Digit DP with bitmask, then subtract: Result = n - countUnique(n). This complementary counting approach simplifies the problem significantly. Time Complexity: O(log n) with digit DP memoization. TutorialsPoint - Numbers With Repeated Digits | Optimal Solution (Digit DP)
Asked in
Google 15 Amazon 8 Microsoft 5
25.0K Views
Medium Frequency
~35 min Avg. Time
850 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