0% completed
Problem Statement
You are given an integer array nums
containing n
integers, integer A
and integer B
.
Return the number of subsets of the nums
have a sum that falls between the values A
and B
(inclusive).
Examples
Example 1:
- Input: nums = [1, -1, 2, 3], A = 1, B = 4
- Expected Output: 10
- Justification: The subsets that satisfy the condition are: [1], [2], [3], [1, 2], [1, 3], [-1, 2], [-1, 3], [1, -1, 2], [-1, 2, 3] and [1, -1, 3]. Each of these subsets has a sum between 1 and 4.
Example 2:
- Input: nums = = [3, 5, -7], A = -4, B = 3
- Expected Output: 5
- Justification: The subsets that satisfy the condition are: [], [3], [5, -7], [3, -7], and [3, 5, -7]. Each of these subsets has a sum between -4 and 3.
Example 3:
- Input: nums = [4, 1, -2, 7, -3], A = 0, B = 6
- Expected Output: 16
- Justification: There are a total 16 subsets which have a sum in the range 0 to 6.
Solution
To solve the problem of counting subsets whose sums fall within a specific range, we use the Meet in the middle approach. The idea is to divide the original array into two halves and then generate all possible subset sums for each half. By working with smaller subsets, we reduce the problem's complexity, making it more manageable. The sums of subsets from the first half are stored in one list, while the sums from the second half are stored in another. The second list is then sorted to enable efficient binary search operations.
After generating and sorting these subset sums, we determine how many pairs of sums from the two lists fall within the given range ([A, B]). For each sum from the first list, we calculate the required range in the second list using simple arithmetic adjustments. Binary search is then employed to quickly count how many sums in the second list fall within this adjusted range. The total count of such valid subsets is returned as the final result. This method significantly reduces the time complexity compared to a brute-force approach, making it effective for handling larger arrays.
Step-by-Step Algorithm
-
Calculate the Length and Midpoint of the Array:
- Start by calculating the length of the input array
nums
and store it in the variablen
. - Calculate the midpoint of the array using
n / 2
and store it in the variablemid
. This will allow us to split the array into two halves.
- Start by calculating the length of the input array
-
Split the Array into Two Halves:
- Use the
Arrays.copyOfRange
method to create two new arrays:set1
andset2
. set1
contains elements from the start ofnums
to the midpoint, i.e.,nums[0]
tonums[mid-1]
.set2
contains elements from the midpoint to the end ofnums
, i.e.,nums[mid]
tonums[n-1]
.
- Use the
-
Generate All Possible Subset Sums for
set1
:- Call the
generateSubsetSums
method withset1
as the input. - The method returns the list
sum1
containing all possible subset sums ofset1
.
- Call the
-
Generate All Possible Subset Sums for
set2
:- Similarly, call the
generateSubsetSums
method withset2
as the input. - The process is identical to the one used for
set1
. - The method returns the list
sum2
containing all possible subset sums ofset2
.
- Similarly, call the
-
Sort the List of Subset Sums for
set2
:- Use
Collections.sort
to sort the listsum2
. Sorting this list allows us to efficiently find how many subset sums fall within a specific range using binary search.
- Use
-
Initialize a Count Variable:
- Initialize a variable
count
to0
. This will be used to keep track of the total number of valid subsets whose sum lies betweenA
andB
.
- Initialize a variable
-
Iterate Over Each Sum in
sum1
:- Use a loop to iterate through each sum
s1
insum1
. - For each
s1
, calculate thelow
andhigh
bounds:low = A - s1
: This is the lower bound of the desired sum range when combined with a sum fromsum2
.high = B - s1
: This is the upper bound of the desired sum range when combined with a sum fromsum2
.
- This step finds the lower and upper bound of the range in
sum2
.
- Use a loop to iterate through each sum
-
Count Valid Sums in
sum2
:- Call the
countInRange
method withsum2
,low
, andhigh
as arguments. - Inside the
countInRange
method:- Call
lowerBound
to find the first index insum2
where the elements are not less thanlow
. - Call
upperBound
to find the first index insum2
where the elements are greater thanhigh
. - The difference
right - left
gives the count of valid sums insum2
that fall within the range[low, high]
.
- Call
- Add this count to the total
count
.
- Call the
-
Return the Total Count:
- After iterating through all sums in
sum1
, return the final value ofcount
. This value represents the total number of subsets whose sum is within the range[A, B]
.
- After iterating through all sums in
Algorithm Walkthrough
-
Input Preparation:
- We start with the array
nums = [1, -1, 2, 3]
and the range[A, B] = [1, 4]
. - Calculate the midpoint
mid = 4 / 2 = 2
.
- We start with the array
-
Split the Array:
- Split
nums
into two halves:set1 = [1, -1]
set2 = [2, 3]
- Split
-
Generate Subset Sums for
set1
:- Generate all possible subset sums for
set1 = [1, -1]
:- Subset
[]
→ Sum0
- Subset
[1]
→ Sum1
- Subset
[-1]
→ Sum-1
- Subset
[1, -1]
→ Sum0
- Subset
- Resulting list
sum1 = [0, 1, -1, 0]
- Generate all possible subset sums for
-
Generate Subset Sums for
set2
:- Generate all possible subset sums for
set2 = [2, 3]
:- Subset
[]
→ Sum0
- Subset
[2]
→ Sum2
- Subset
[3]
→ Sum3
- Subset
[2, 3]
→ Sum5
- Subset
- Resulting list
sum2 = [0, 2, 3, 5]
- Generate all possible subset sums for
-
Sort
sum2
:- Sort
sum2
, though it is already sorted in this case:sum2 = [0, 2, 3, 5]
.
- Sort
-
Count Valid Subsets:
-
Initialize
count = 0
. -
Iterate over each sum
s1
insum1
and calculate the range[low, high]
for valid sums insum2
:- For
s1 = 0
:low = 1 - 0 = 1
high = 4 - 0 = 4
- In
sum2
, valid sums are2
and3
. - Valid subset count = 2.
- Update
count = count + 2 = 2
.
- For
s1 = 1
:low = 1 - 1 = 0
high = 4 - 1 = 3
- In
sum2
, valid sums are0
,2
, and3
. - Valid subset count = 3.
- Update
count = count + 3 = 5
.
- For
s1 = -1
:low = 1 - (-1) = 2
high = 4 - (-1) = 5
- In
sum2
, valid sums are2
,3
, and5
. - Valid subset count = 3.
- Update
count = count + 3 = 8
.
- For
s1 = 0
:low = 1 - 0 = 1
high = 4 - 0 = 4
- In
sum2
, valid sums are2
and3
. - Valid subset count = 2.
- Update
count = count + 2 = 10
.
- For
-
-
Final Output:
- After processing all sums in
sum1
, the final count of valid subsets is10
. - Return
10
as the output.
- After processing all sums in
Code
Complexity Analysis
Time Complexity
- Generating Subset Sums:
- For each of the two halves of the array (
Set1
andSet2
), the code generates all possible subset sums. Since there areN/2
elements in each half, the number of subsets is 2<sup>(N/2)</sup>. This gives us O(2<sup>(N/2)</sup>) operations for each half.
- For each of the two halves of the array (
- Sorting the Subset Sums (
Sum2
):- Sorting the
Sum2
list takes O(2<sup>(N/2)</sup> * log(2<sup>(N/2)</sup>)), which simplifies to O(2<sup>(N/2)</sup> * N/2) or O(N * 2<sup>(N/2)</sup>).
- Sorting the
- Binary Search Operations:
- For each sum in
Sum1
, we perform a binary search onSum2
to count the number of valid pairs. This step takes O(2<sup>(N/2)</sup> * log(2<sup>(N/2)</sup>))or
O(2<sup>(N/2)</sup> * N/2).
- For each sum in
- Total Time Complexity:
- The overall time complexity is O(2<sup>(N/2)</sup> * N).
Space Complexity
- Storage for Subset Sums (
Sum1
andSum2
):- We need to store the subset sums for both halves, which requires O(2<sup>(N/2)</sup>) space for each list. Thus, the total space complexity is O(2<sup>(N/2)</sup>).
.....
.....
.....
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible