Prime Subset Selection II - Solution & Explanation
Problem Statement
You are given two integers n and s.
Consider all prime numbers less than or equal to n. Select a subset of these primes such that:
- Each prime can be selected at most once.
- The sum of the selected primes is as large as possible while remaining less than or equal to
s. - Among subsets with the maximum sum, select one containing the fewest primes.
- If multiple subsets remain tied, select the one whose elements, written in increasing order, form the lexicographically smallest array.
Return an integer array containing the selected primes in increasing order. If no valid non-empty subset exists, return an empty array.
Example 1:
Input: n = 7, s = 20
Output: [2, 3, 5, 7]
Explanation:
- The prime numbers less than or equal to
n = 7are 2, 3, 5, and 7. - The sum of all these primes is
2 + 3 + 5 + 7 = 17, which is less than or equal tos = 20. - Thus, the answer is
[2, 3, 5, 7].
Example 2:
Input: n = 15, s = 18
Output: [5,13]
Explanation:
- The prime numbers less than or equal to 15 are 2, 3, 5, 7, 11, and 13.
- The subsets with sum 18 are
[5, 13],[7, 11],[2, 3, 13], and[2, 5, 11]. Since this sum equalss, it is the maximum possible sum. - Among these subsets,
[5, 13]and[7, 11]contain the fewest primes: two. - Between these two subsets,
[5, 13]is lexicographically smaller because its first element, 5, is smaller than 7. Thus, the answer is[5, 13].
Example 3:
Input: n = 5, s = 1
Output: []
Explanation:
- The smallest prime number is 2, which is greater than
s = 1. - Thus, no prime can be selected, so the answer is an empty array.
Constraints:
1 <= n <= 10001 <= s <= 1000
Approach Overview
Problem Overview: You get an array of integers and must choose a subset that satisfies a prime-based condition. The goal is to find the best valid selection, usually the largest or the one that meets a count or sum target. Primality checks are the bottleneck, so precompute them once.
Approach 1: Brute Force Over All Subsets (O(2^n * n) time, O(n) space)
Generate every subset with recursion or bitmasks from 0 to 2^n - 1. For each subset, test the prime condition by checking each element with trial division up to its square root. Keep the best valid subset seen so far. This works only for small n, since the subset count doubles with every element. Use it to confirm your understanding of the constraint before optimizing.
Approach 2: Backtracking with Pruning (O(2^n) worst case, O(n) space)
Build the subset one element at a time and drop branches early. If the current partial selection already violates the condition, or cannot reach the best answer found so far, stop. Pruning helps a lot on inputs with many invalid elements, but the worst case stays exponential. Prefer this when the constraint is monotone, meaning once a partial set fails, every superset fails too.
Approach 3: Sieve Plus Dynamic Programming (O(n * k + M log log M) time, O(M + n * k) space)
Run the Sieve of Eratosthenes once up to the maximum value M to mark primes in O(M log log M). Then replace repeated primality tests with an O(1) lookup. Model the selection as a DP table where each state tracks the best result for a prefix of the array and a small parameter, such as the number of chosen elements or the running sum modulo a value. Each element either joins the subset or gets skipped, so the transition is constant time per state. This turns exponential enumeration into polynomial work.
Recommended for interviews: Interviewers expect you to start with brute force to show you understand the search space, then move to the sieve and DP approach. The brute force shows correctness reasoning. The sieve plus DP shows you can separate precomputation from the main loop and recognize overlapping subproblems. Explain the state definition and the transition before you write code.
Solutions for this problem are being prepared.
Try solving it yourselfDetailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Over Subsets | O(2^n * n) | O(n) | Very small n, verifying correctness |
| Backtracking with Pruning | O(2^n) worst case | O(n) | Many invalid elements, monotone constraints |
| Sieve Plus Dynamic Programming | O(n * k + M log log M) | O(M + n * k) | General case, large n with bounded values |
Video Solutions (4)
Leetcode 4081 | Prime Subset Selection II | Leetcode weekly contest 523 | Dynamic Programming
Frequently Asked Questions
Is Prime Subset Selection II easy or hard?
Prime Subset Selection II Python solution?
How to solve Prime Subset Selection II in O(n)?
What is the best approach for Prime Subset Selection II?
What data structure is used in Prime Subset Selection II?
What is the time complexity of Prime Subset Selection II?
Is Prime Subset Selection II asked at Google, Amazon, or Meta?
Ready to solve this problem?
Practice Prime Subset Selection II with our built-in code editor and test cases.
Practice on FleetCodeProblem Info
Table of Contents
Practice this problem
Open in Editor