709863. Smallest Subset with Greater Sum

Easy

Here is the detailed Markdown blog post for the problem "Smallest Subset with Greater Sum":

Smallest Subset with Greater Sum

Slug: smallest-subset-with-greater-sum

Difficulty: Easy

Id: 709863

Topic Tags: Arrays, Greedy, Sorting, Data Structures, Algorithms

Company Tags: None

Summary

Given a set of integers, find the smallest subset whose sum is greater than or equal to a given target sum. This problem involves finding the minimum-sized subset that meets a certain condition.

Detailed Explanation

To solve this problem, we can use a greedy algorithm. The idea is to keep adding elements to our subset as long as their sum is less than the target sum. When we reach the target sum or exceed it, we stop and return the current subset.

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

  1. Initialize an empty subset result and a variable current_sum set to 0.
  2. Sort the input array in non-decreasing order.
  3. Iterate through the sorted array. For each element, check if adding it to result would exceed the target sum. If not, add it to result and update current_sum.
  4. When we reach an element that would exceed the target sum or when we reach the end of the array, return result.

Time complexity: O(n log n) due to sorting Space complexity: O(1) since we only use a few extra variables

Optimized Solutions

Java

View on GeeksforGeeks
public static List<Integer> smallestSubset(int[] arr, int targetSum) {
    Arrays.sort(arr);
    List<Integer> result = new ArrayList<>();
    int currentSum = 0;
    
    for (int num : arr) {
        if (currentSum + num > targetSum) break;
        result.add(num);
        currentSum += num;
    }
    
    return result;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.