You are given an array of integers
Return the number of non-empty subsequences of
Output: 4
Explanation: There are 4 subsequences that satisfy the condition.
[3] -> Min value + max value <= target (3 + 3 <= 9)
[3,5] -> (3 + 5 <= 9)
[3,5,6] -> (3 + 6 <= 9)
[3,6] -> (3 + 6 <= 9)
Output: 6
Explanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]
Output: 61
Explanation: There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).
Number of valid subsequences (63 - 2 = 61).
Constraints:
1 <= nums.length <= 105 1 <= nums[i] <= 106 1 <= target <= 106
Contents
Solution 1 - Sort input array, and search for pairs of left and right numbers that satisfy <= target condition
In this approach, we are going to sort the input array first, then find matching pairs of numbers on left and right ends of array using two pointers and calculate number of subsequences that can be formed using the numbers between those pair of numbers.
Consider an example with
-
Say we don't sort the array, then the sub sequences with
target <= 9 will be [3], [3,6], [3,6,5], [3,5]. -
Say we sort the array, then the array becomes
[3, 5, 6, 7] sub sequences withtarget <= 9 will be [3], [3,5], [3,5,6], [3,6].
Implementation steps:
- As a first step, sort the input array.
-
Then, declare following variables:
-
result : to hold the result and return, initialize this with0 . -
modulo : value that we will be using to divide with as mentioned in the problem statement, initialize this with109 +7 . -
left : left pointer for the array, intiialize this with 0. -
right : right pointer for the array, initialize this with nums.length - 1.
-
-
Next, loop through the input array while two pointers
left andright don't intersect with each other and check:-
If
nums[left] + nums[right] <= target , then count the number of subsequences that can be formed using the numbers fromleft element toright pointer and incrementleft pointer. There will be2(right- left) number of subsequences withleft element being present in all sunsubsequences.
For example, consider if the subsequence is[2, 3, 4] , and sub sequences with the 2 being the first element are [2], [2,3], [2,3,4] and [2,4], so we can take it as22 , since the array is 0-indexed, we can simply take2right- left = 22-0 = 4 .After computing number of subsequences, apply modulo on the result to avoid overflow as per problem statement and store it in result . -
Otherwise, decrement
right pointer.
-
If
-
Finally return the
result .
Complexity Analysis:
Time complexity: Above code runs in O(n log n) time where
Space complexity: O(1), assuming that sorting will be done using in-place sorting algorithms like
Above implementations source code can be found at