Skip to content

Commit 71a1510

Browse files
committed
update 0974 english readme
1 parent 8fbe67c commit 71a1510

File tree

1 file changed

+23
-1
lines changed
  • solution/0900-0999/0974.Subarray Sums Divisible by K

1 file changed

+23
-1
lines changed

solution/0900-0999/0974.Subarray Sums Divisible by K/README_EN.md

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,29 @@ tags:
5454

5555
<!-- solution:start -->
5656

57-
### Solution 1
57+
### Solution 1: Hash Table + Prefix Sum
58+
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.
62+
63+
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$.
67+
68+
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$.
76+
77+
> Note: if $s$ is negative, adjust it to be non-negative by adding $k$ and taking modulo $k$ again.
78+
79+
The time complexity is $O(n)$ and space complexity is $O(n)$ where $n$ is the length of the array $nums$.
5880

5981
<!-- tabs:start -->
6082

0 commit comments

Comments
 (0)