You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/0900-0999/0974.Subarray Sums Divisible by K/README_EN.md
+14-12Lines changed: 14 additions & 12 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -57,22 +57,24 @@ tags:
57
57
### Solution 1: Hash Table + Prefix Sum
58
58
59
59
1.**Key Insight**:
60
-
- If there exist indices $i$ and $j$ such that $i \leq j$, and the sum of the subarray $nums[i, ..., j]$ is divisible by $k$, then $(s_j - s_i) \bmod k = 0$, this implies: $s_j \bmod k = s_i \bmod k$
61
-
- We can use a hash table to count the occurrences of prefix sums modulo $k$ to efficiently check for subarrays satisfying the condition.
60
+
61
+
- If there exist indices $i$ and $j$ such that $i \leq j$, and the sum of the subarray $nums[i, ..., j]$ is divisible by $k$, then $(s_j - s_i) \bmod k = 0$, this implies: $s_j \bmod k = s_i \bmod k$
62
+
- We can use a hash table to count the occurrences of prefix sums modulo $k$ to efficiently check for subarrays satisfying the condition.
62
63
63
64
2.**Prefix Sum Modulo**:
64
-
- Use a hash table $cnt$ to count occurrences of each prefix sum modulo $k$.
65
-
- $cnt[i]$ represents the number of prefix sums with modulo $k$ equal to $i$.
66
-
- Initialize $cnt[0] = 1$ to account for subarrays directly divisible by $k$.
65
+
66
+
- Use a hash table $cnt$ to count occurrences of each prefix sum modulo $k$.
67
+
- $cnt[i]$ represents the number of prefix sums with modulo $k$ equal to $i$.
68
+
- Initialize $cnt[0] = 1$ to account for subarrays directly divisible by $k$.
67
69
68
70
3.**Algorithm**:
69
-
- Let a variable $s$ represent the running prefix sum, starting with $s = 0$.
70
-
- Traverse the array $nums$ from left to right.
71
-
- For each element $x$:
72
-
- Compute $s = (s + x) \bmod k$.
73
-
- Update the result: $ans += cnt[s]$.
74
-
- Increment $cnt[s]$ by $1$.
75
-
- Return the result $ans$.
71
+
- Let a variable $s$ represent the running prefix sum, starting with $s = 0$.
72
+
- Traverse the array $nums$ from left to right.
73
+
- For each element $x$:
74
+
- Compute $s = (s + x) \bmod k$.
75
+
- Update the result: $ans += cnt[s]$.
76
+
- Increment $cnt[s]$ by $1$.
77
+
- Return the result $ans$.
76
78
77
79
> Note: if $s$ is negative, adjust it to be non-negative by adding $k$ and taking modulo $k$ again.
0 commit comments