8000 Create Count of Interesting Subarrays.py · erjan/coding_exercises@4010372 · GitHub
[go: up one dir, main page]

Skip to content

Commit 4010372

Browse files
authored
Create Count of Interesting Subarrays.py
1 parent fdb322d commit 4010372

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Count of Interesting Subarrays.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
'''
2+
You are given a 0-indexed integer array nums, an integer modulo, and an integer k.
3+
4+
Your task is to find the count of subarrays that are interesting.
5+
6+
A subarray nums[l..r] is interesting if the following condition holds:
7+
8+
Let cnt be the number of indices i in the range [l, r] such that nums[i] % modulo == k. Then, cnt % modulo == k.
9+
Return an integer denoting the count of interesting subarrays.
10+
11+
Note: A subarray is a contiguous non-empty sequence of elements within an array.
12+
'''
13+
14+
15+
#bad solution
16+
17+
class Solution:
18+
def countInterestingSubarrays(self, nums: List[int], modulo: int, k: int) -> int:
19+
20+
21+
res = 0
22+
23+
n = len(nums)
24+
25+
for i in range(n):
26+
prefsum = [nums[i]]
27+
28+
for j in range(i, n):
29+
prefsum.append(prefsum[-1] +nums[j])
30+
31+
for q in range(len(prefsum)):
32+
if nums[q]%modulo == k:
33+
res +=1
34+
return res
35+
36+
--------------------------------------------------------------------------------------------
37+
38+
class Solution:
39+
def countInterestingSubarrays(self, nums: List[int], modulo: int, k: int) -> int:
40+
prefixModCount = {0: 1}
41+
prefixSum = 0
42+
result = 0
43+
44+
for num in nums:
45+
if num % modulo == k:
46+
prefixSum += 1
47+
remainder = prefixSum % modulo
48+
target = (remainder - k) % modulo
49+
result += prefixModCount.get(target, 0)
50+
prefixModCount[remainder] = prefixModCount.get(remainder, 0) + 1
51+
52+
return result

0 commit comments

Comments
 (0)
0