Skip to content

Commit c80aacd

Browse files
committed
Time: 87 ms (23.57%), Space: 38.3 MB (27.49%) - LeetHub
1 parent 91290ec commit c80aacd

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# time complexity: O(n)
2+
# space complexity: O(n)
3+
from typing import List
4+
5+
6+
class Solution:
7+
def minSubarray(self, nums: List[int], p: int) -> int:
8+
n = len(nums)
9+
totalSum = 0
10+
for num in nums:
11+
totalSum = (totalSum + num) % p
12+
target = totalSum % p
13+
if target == 0:
14+
return 0
15+
16+
modMap = {
17+
0: -1
18+
}
19+
currentSum = 0
20+
minLen = n
21+
for i in range(n):
22+
currentSum = (currentSum + nums[i]) % p
23+
needed = (currentSum - target + p) % p
24+
if needed in modMap:
25+
minLen = min(minLen, i - modMap[needed])
26+
modMap[currentSum] = i
27+
return -1 if minLen == n else minLen
28+
29+
30+
nums = [3, 1, 4, 2]
31+
p = 6
32+
print(Solution().minSubarray(nums, p))

0 commit comments

Comments
 (0)