704510. Subset with sum divisible by k

Medium

Subset with sum divisible by k

Slug: subset-with-sum-divisible-by-m2546

Difficulty: Medium

Id: 704510

Topic Tags: Dynamic Programming, Algorithms, Arrays, Data Structures

Company Tags: None

Summary

The problem is to find all subsets of a given array whose sum is divisible by k. This problem involves dynamic programming and arrays.

Detailed Explanation

To solve this problem, we can use dynamic programming to generate all possible subsets of the input array. We can then iterate through each subset and check if its sum is divisible by k. If it is, we add it to our result set.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty set result to store the subsets whose sum is divisible by k.
  2. Iterate through each element i in the input array.
  3. For each i, generate all possible subsets that include i. You can do this by iterating through each previous subset and adding i to it.
  4. For each subset, calculate its sum using a loop or recursive function.
  5. Check if the sum is divisible by k. If it is, add the subset to the result set.
  6. Return the result set.

Here's an ASCII art diagram illustrating the dynamic programming approach:

       +---------------+
       |  Input Array  |
       +---------------+
                  |
                  |  Generate subsets
                  v
       +---------------+
       |  Subsets with i  |
       +---------------+
                  |
                  |  Calculate sum
                  |  Check if divisible by k
                  v
       +---------------+
       |  Result Set     |
       +---------------+

Time complexity: O(n * 2^n), where n is the length of the input array. This is because we generate all possible subsets, and there are 2^n subsets in total. Space complexity: O(n), as we need to store the result set.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.*;

public class SubsetSumDivisible {
    public List<List<Integer>> findSubsets(int[] arr, int k) {
        Set<List<Integer>> result = new HashSet<>();
        for (int i : arr) {
            Set<List<Integer>> subsetsWithI = new HashSet<>();
            for (List<Integer> subset : result) {
                subsetsWithI.add(new ArrayList<>(subset) {{
                    add(i);
                }});
            }
            for (List<Integer> subset : subsetsWithI) {
                int sum = 0;
                for (int num : subset) {
                    sum += num;
                }
                if (sum % k == 0) {
                    result.add(new ArrayList<>(subset));
                }
            }
        }
        return new ArrayList<>(result);
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.