K-Subarrays

Sort by

recency

|

2 Discussions

|

  • + 0 comments
    class Result {
    
    /*
     * Complete the 'kSub' function below.
     *
     * The function is expected to return a LONG_INTEGER.
     * The function accepts following parameters:
     *  1. INTEGER k
     *  2. INTEGER_ARRAY nums
     */
    
    public static long kSub(int k, List<Integer> nums) {
        long count =0;
        long[] mod = new long[k];
        mod[0]=1;
        long sum = 0;
    
        for(int i = 0;i<nums.size();i++){
            sum+=nums.get(i);
            int rem =(int) sum%k;
            count+=mod[rem];
            mod[rem]++;
    
        }
        return count;
    
        }
                }
    
    }
    

    }

  • + 0 comments

    Worked with all test cases in Java

     public static long kSub(int k, List<Integer> nums) {
    
            long currSum = 0;
            long[] sum = new long[nums.size()];
            long count = 0;
            
            Map<Integer, Long> remainderMap = new HashMap<>();
            remainderMap.put(0, 1L);
            
            for(int i = 0 ; i < nums.size(); i++){
                currSum = currSum + nums.get(i);
                sum[i] = currSum;
           
                int remainder = (int)(sum[i] % k);
                
                if(!remainderMap.containsKey(remainder)){
                    remainderMap.put(remainder, 1L);
                }else{
                    long frequency = remainderMap.get(remainder);
                    count = count + frequency;
                    remainderMap.put(remainder, frequency + 1); 
                }
                
            }
    
        return count;
    }
    

    }

No more comments