|
54 | 54 |
|
55 | 55 | <!-- solution:start -->
|
56 | 56 |
|
57 | | -### Solution 1 |
| 57 | +### Solution 1: Hash Table + Prefix Sum |
| 58 | + |
| 59 | +1. **Key Insight**: |
| 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. |
| 63 | + |
| 64 | +2. **Prefix Sum Modulo**: |
| 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$. |
| 69 | + |
| 70 | +3. **Algorithm**: |
| 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$. |
| 78 | + |
| 79 | +> Note: if $s$ is negative, adjust it to be non-negative by adding $k$ and taking modulo $k$ again. |
| 80 | + |
| 81 | +The time complexity is $O(n)$ and space complexity is $O(n)$ where $n$ is the length of the array $nums$. |
58 | 82 |
|
59 | 83 | <!-- tabs:start -->
|
60 | 84 |
|
|
0 commit comments