Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Subarray Sum Divisible by K (Leetcode 974) #306

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Medium/Subarray Sum Divisible by K.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution {
public int subarraysDivByK(int[] nums, int k) {
int count =0;
int sum =0;
int rem =0;
HashMap<Integer,Integer> map = new HashMap<>();
map.put(0,1); //initially sum is 0 and it appeared once already

for(int num:nums){
sum+=num;
rem=sum%k;

if(rem<0){
rem+=k; // if k=7 and rem = -2 then rem+k =2 and the gap betwen 2 and -5 is 7 which is divisible by 7
}
if(map.containsKey(rem)){
count+=map.get(rem);
map.put(rem, map.get(rem)+1);
}
else{
map.put(rem,1);
}
}
System.out.println(map.entrySet());
return count;
}
}