Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b5605cd

Browse files
docs: update solution to lc problem: No.0974 (doocs#3870)
1 parent 8da7210 commit b5605cd

File tree

1 file changed

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

1 file changed

+25
-1
lines changed

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

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

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

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$.
5882

5983
<!-- tabs:start -->
6084

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /