Skip to content

Commit f6f332e

Browse files
authored
Update count-numbers-with-unique-digits-ii.py
1 parent 3b0d1d9 commit f6f332e

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

Python/count-numbers-with-unique-digits-ii.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# Time: O(logb)
22
# Space: O(logb)
33

4-
# combinatorics
4+
# hash table, bitmasks, combinatorics
55
class Solution(object):
66
def numberCount(self, a, b):
77
"""
@@ -14,13 +14,17 @@ def nPr(n, k):
1414
while len(fact) <= n: # lazy initialization
1515
fact.append(fact[-1]*len(fact))
1616
return fact[n]//fact[n-k]
17+
18+
def popcount(x):
19+
return bin(x).count('1')
1720

1821
def count(x):
1922
digits = map(int, str(x))
2023
result = 9*sum(nPr(9, i) for i in xrange(len(digits)-1))
2124
lookup = 0
2225
for i, d in enumerate(digits):
23-
result += sum(lookup&(1<<j) == 0 for j in xrange(int(i == 0), d))*nPr(10-(i+1), len(digits)-(i+1))
26+
mask = lookup&(((1<<d)-1)-int(i == 0))
27+
result += ((d-int(i == 0))-popcount(mask))*nPr(10-(i+1), len(digits)-(i+1))
2428
if lookup&(1<<d):
2529
break
2630
lookup |= 1<<d
@@ -31,7 +35,7 @@ def count(x):
3135

3236
# Time: O(blogb)
3337
# Space: O(1)
34-
# hash table
38+
# hash table, bitmasks
3539
class Solution2(object):
3640
def numberCount(self, a, b):
3741
"""

0 commit comments

Comments
 (0)