File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Time: O(logn)
2
+ # Space: O(logn)
3
+
4
+ class Solution (object ):
5
+ def numDupDigitsAtMostN (self , N ):
6
+ """
7
+ :type N: int
8
+ :rtype: int
9
+ """
10
+ def P (m , n ):
11
+ result = 1
12
+ while n > 0 :
13
+ result *= m - n + 1
14
+ n -= 1
15
+ return result
16
+
17
+ digits = map (int , str (N + 1 ))
18
+ result = 0
19
+
20
+ # Given 321
21
+ #
22
+ # 1. count numbers without repeated digits:
23
+ # - X
24
+ # - XX
25
+ for i in xrange (1 , len (digits )):
26
+ result += P (9 , 1 )* P (9 , i - 1 )
27
+
28
+ # 2. count numbers without repeated digits:
29
+ # - 1XX ~ 3XX
30
+ # - 30X ~ 32X
31
+ # - 320 ~ 321
32
+ prefix_set = set ()
33
+ for i , x in enumerate (digits ):
34
+ for y in xrange (1 if i == 0 else 0 , x ):
35
+ if y in prefix_set :
36
+ continue
37
+ result += P (9 - i , len (digits )- i - 1 )
38
+ if x in prefix_set :
39
+ break
40
+ prefix_set .add (x )
41
+ return N - result
You can’t perform that action at this time.
0 commit comments