forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
k-divisible-elements-subarrays.py
89 lines (79 loc) · 2.3 KB
/
k-divisible-elements-subarrays.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# Time: O(n^2)
# Space: O(t), t is the size of trie
import collections
# trie
class Solution(object):
def countDistinct(self, nums, k, p):
"""
:type nums: List[int]
:type k: int
:type p: int
:rtype: int
"""
_trie = lambda: collections.defaultdict(_trie)
trie = _trie()
result = 0
for i in xrange(len(nums)):
cnt = 0
curr = trie
for j in xrange(i, len(nums)):
cnt += (nums[j]%p == 0)
if cnt > k:
break
if nums[j] not in curr:
result += 1
curr = curr[nums[j]]
return result
# Time: O(n^2) on average, worst is O(n^3)
# Space: O(n)
import collections
# rolling hash
class Solution2(object):
def countDistinct(self, nums, k, p):
"""
:type nums: List[int]
:type k: int
:type p: int
:rtype: int
"""
MOD, P = 10**9+7, 113
def check(nums, lookup, l, i):
return all(any(nums[i+k] != nums[j+k] for k in xrange(l)) for j in lookup)
result = 0
cnt, h = [0]*len(nums), [0]*len(nums)
for l in xrange(1, len(nums)+1):
lookup = collections.defaultdict(list)
for i in xrange(len(nums)-l+1):
cnt[i] += (nums[i+l-1]%p == 0)
if cnt[i] > k:
continue
h[i] = (h[i]*P+nums[i+l-1])%MOD
if not check(nums, lookup[h[i]], l, i):
continue
lookup[h[i]].append(i)
result += 1
return result
# Time: O(n^2)
# Space: O(n)
# rolling hash
class Solution3(object):
def countDistinct(self, nums, k, p):
"""
:type nums: List[int]
:type k: int
:type p: int
:rtype: int
"""
MOD, P = 10**9+7, 200
result = 0
cnt, h = [0]*len(nums), [0]*len(nums)
for l in xrange(1, len(nums)+1):
lookup = set()
for i in xrange(len(nums)-l+1):
cnt[i] += (nums[i+l-1]%p == 0)
if cnt[i] > k:
continue
h[i] = (h[i]*P+nums[i+l-1])%MOD
lookup.add(h[i])
result += len(lookup)
return result