Longest subarray with sum divisible by K | Practice | GeeksforGeeks

Given an array containing N integers and a positive integer K, find the length of the longest sub array with sum of the elements divisible by the given value K.
Example 1:
Input:
A[] = {2, 7, 6, 1, 4, 5}
K = 3
Output: 4
Explanation:The subarray is {7, 6, 1, 4}
with sum 18, which is divisible by 3.
Example 2:
Input:
A[] = {-2, 2, -5, 12, -11, -1, 7}
K = 3
Output: 5
Explanation:
The subarray is {2,-5,12,-11,-1} with
sum -3, which is divisible by 3.
 
Your Task:
The input is already taken care of by the driver code. You only need to complete the function longSubarrWthSumDivByK() that takes an array (arr), sizeOfArray (n), positive integer K, and return the length of the longest subarray which has sum divisible by K. The driver code takes care of the printing.

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).â€‹
Constraints:
1<=N,K<=106
-105<=A[i]<=105
 
+2
neeramrutia2 months ago
 HashMap<Integer,Integer> hm=new HashMap<>();      int sum=0;      hm.put(0,-1);      int i;      int rem;      int maxl=0;      for(i=0;i<n;i++)      {          sum=sum+a[i];          rem=sum%k;          if(rem<0)          rem=rem+k;          if(hm.containsKey(rem))          {              maxl=Math.max(maxl,i-hm.get(rem));          }          else          {              hm.put(rem,i);          }      }      return maxl;
0
sy9924552 months ago
  int longSubarrWthSumDivByK(int arr[], int n, int k)
    {
        HashMap<Integer,Integer> map = new HashMap<>();
        int sum = 0;
        int rem = 0;
        int mLen = 0;
        map.put(0  , -1);
        for(int i=0;i<n;i++){
            sum+=arr[i];
            rem = sum % k;
            if(rem < 0) rem+=k;
            if(map.containsKey(rem)){
                mLen = Math.max(mLen , i - map.get(rem));
            }else{
                map.put(rem , i);
            }
        }
       return mLen;
    }
0
sy992455
This comment was deleted.
0
akkeshri140420012 months ago
int longSubarrWthSumDivByK(int arr[], int n, int k)
{
    // Complete the function
    unordered_map<int,int>m;
    m[0]=-1;
    int maxi=0;
    int sum=0;
    for(int i=0;i<n;i++){
        sum+=arr[i];
        int rem=sum%k;
        if(rem<0){
            rem+=k;
        }
        if(m.find(rem)!=m.end()){
            int len=i-m[rem];
            if(len>maxi){
                maxi=len;
            }
        }
        else if(m.find(rem)==m.end()){
            m[rem]=i;
        }
    }
    return maxi;
    
}
0
asissrmakumar6663 months ago
JAVA || prefixSum || Total Time Taken: 0.9/5.4
class Solution{
    int longSubarrWthSumDivByK(int arr[], int n, int k)
    {
       HashMap<Integer,Integer> hs=new HashMap<>();
        hs.put(0,-1);
        int pS=0,max=0;
        for(int i=0;i<arr.length;i++){
            pS=((pS+arr[i])%k+k)%k;
          
            if(hs.get(pS)!=null){
                max=Math.max(max,i-hs.get(pS));
            }
            else hs.put(pS,i);
        }
        return max;
       
    }
 
}
 
0
hrithikrsgupta3 months ago
This mod type of questions have so many edge cases :/
0
aloksinghbais023 months ago
C++ solution having time complexity O(N) and space complexity as O(N) is as follows :-
Note :- Similar question in which we find total subarrays having sum divisible by k.
 
Execution Time :- 0.5 / 1.8 sec
 
int longSubarrWthSumDivByK(int arr[], int n, int k){    unordered_map<int,int> firstLastInd;    unordered_map<int,bool> mp;    int len = 0;    int sum = 0; mp[sum] = true; firstLastInd[0] = 0;    for(int i=0; i<n; i++){        sum += arr[i];        int rem = sum % k;        if(rem < 0) rem += k;        if(mp[rem]){            len = max(len,(i - firstLastInd[rem] + 1));        }                mp[rem] = true;        if(firstLastInd[rem] == 0 && rem)                                        firstLastInd[rem] = i+1;    }        return (len);}
0
soumo2k154 months ago
int longSubarrWthSumDivByK(int a[], int n, int k){    map<int,int>m;    int sum=0,rem=0,ans=0;    for(int i=0;i<n;i++){        sum+=a[i];        rem=sum%k;        if(rem<0)rem+=k;        if(!rem)ans=i+1;        if(m.find(rem)==m.end())m[rem]=i;        if(m.find(rem)!=m.end())ans=max(ans,i-m[rem]);    }    return ans;}
0
rohanpandey7494 months ago
C++ solution:
class Solution{
public:	
	int longSubarrWthSumDivByK(int arr[], int n, int k)
	{
	    // Complete the function
	    unordered_map<int,int>mp;
	    mp[0]=-1;
	    int sum=0, answer=0;
	    int cur;
	    for(int i=0;i<n;i++){
	        sum+=arr[i];
	        cur=((sum%k)+k)%k;
	        
	   if(mp.find(cur)!=mp.end()){
	        answer=max(answer,i-mp[cur]);
	        }
	        else{
	            mp[cur]=i;
	        }
	    }
	    return answer;
	}
};
0
rajput91894 months ago

class Solution{
public:	
	int longSubarrWthSumDivByK(int arr[], int n, int k)
	{
	    unordered_map<int,int>mp;
	    mp.insert({0,-1});
	    int prefix=0;
	    int ans=0;
	    for(int i=0;i<n;++i)
	    {
	        prefix+=arr[i];
	        int rem=prefix%k;
	        
	        if(rem<0)
	            rem+=k;
	            
	        if(mp.find(rem)!=mp.end())
	        {
	            ans=max(ans,i-mp[rem]);
	        }
	        else
	        {
	            mp.insert({rem,i});
	        }
	    }
	    return ans;
	}
};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.