878166. Split array into minimum subsets

Easy

Split array into minimum subsets

Slug: split-array-into-minimum-subsets

Difficulty: Easy

Id: 878166

Topic Tags: Sorting, Arrays, Hash

Company Tags: None

Summary

Given an integer array arr, the goal is to divide it into a minimum number of subsets such that the sum of each subset is equal. The array can be divided in any way as long as all elements are included in one of the subsets.

Detailed Explanation

To solve this problem, we can use a greedy approach. First, sort the array in descending order based on its values. Then, create a subset by adding elements from the sorted array until the sum of the subset is equal to or greater than the average sum of all subsets.

Here's the step-by-step breakdown:

  1. Sort the array arr in descending order.
  2. Initialize an empty list subsets to store the minimum number of subsets.
  3. Calculate the total sum total_sum of the array.
  4. Calculate the target sum for each subset target_sum by dividing the total sum by the number of subsets.
  5. Iterate over the sorted array:
    • If the current element is less than or equal to the target sum, add it to the current subset and update the target sum.
    • If the current element is greater than the target sum, start a new subset with this element as its first element and reset the target sum.
  6. Add the last subset to the subsets list.

The time complexity of this algorithm is O(n log n) due to the sorting step, where n is the number of elements in the array. The space complexity is O(1), as we only use a constant amount of space to store the subsets and other variables.

Optimized Solutions

Java

View on GeeksforGeeks
public class Solution {
    public List<List<Integer>> splitArray(int[] arr) {
        Arrays.sort(arr);
        int totalSum = 0;
        for (int num : arr) {
            totalSum += num;
        }
        int targetSum = totalSum / arr.length;
        List<List<Integer>> subsets = new ArrayList<>();
        int currentSum = 0;
        List<Integer> subset = new ArrayList<>();
        for (int num : arr) {
            if (currentSum + num <= targetSum) {
                currentSum += num;
                subset.add(num);
            } else {
                subsets.add(subset);
                subset = new ArrayList<>();
                currentSum = num;
                subset.add(num);
            }
        }
        subsets.add(subset);
        return subsets;
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.