702918. Subarray Sum Divisible By K

Medium

Subarray Sum Divisible By K

Summary

Given an array nums and an integer k, find all subarrays that sum up to a value divisible by k. This problem involves arrays, data structures, and prefix sums.

Detailed Explanation

The key idea is to use prefix sums to efficiently calculate the sum of any subarray. We can iterate through the array and for each element, calculate the sum of the subarray ending at that element using the previously calculated prefix sum. Then, we check if this sum is divisible by k and if it is, add the subarray to our result set.

Here's a step-by-step breakdown:

  1. Initialize an empty list result to store the subarrays.
  2. Calculate the total sum of the array using a single pass through the array.
  3. Iterate through the array again:
    • For each element num, calculate the prefix sum ps up to that point.
    • Check if ps % k == 0. If it is, add all subarrays ending at num to result.
  4. Return result.

Time complexity: O(n), where n is the length of the array. We iterate through the array twice.

Space complexity: O(n), for storing the prefix sums and result set.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.ArrayList;
import java.util.List;

public class SubarraySumDivisibleByK {
    public List<List<Integer>> subarraysWithSumDivisibleByK(int[] nums, int k) {
        List<List<Integer>> result = new ArrayList<>();
        long totalSum = 0;
        for (int num : nums) {
            totalSum += num;
        }
        
        for (int i = 0; i < nums.length; i++) {
            long ps = 0;
            for (int j = i; j >= 0; j--) {
                ps += nums[j];
                if (ps % k == 0) {
                    List<Integer> subarray = new ArrayList<>();
                    for (int m = j; m <= i; m++) {
                        subarray.add(nums[m]);
                    }
                    result.add(subarray);
                }
            }
        }
        
        return result;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.