Taro Logo

Sum of Subsequence Widths

#1 Most AskedHard
Topics:
ArraysTwo PointersGreedy Algorithms

The width of a sequence is the difference between the maximum and minimum elements in the sequence.

Given an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 109 + 7.

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].

Example 1:

Input: nums = [2,1,3]
Output: 6
Explanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].
The corresponding widths are 0, 0, 0, 1, 1, 2, 2.
The sum of these widths is 6.

Example 2:

Input: nums = [2]
Output: 0

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 105

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the length of the input array `nums` and the range of values inside it?
  2. Can the input array contain duplicate elements, and if so, should they be treated as distinct elements based on their positions or as identical values?
  3. How should we handle empty inputs or an array with only a single element, given that a single-element subsequence has a width of zero?
  4. Since the problem mentions subsequences (which do not require contiguous elements), does the original order of elements in `nums` matter for our calculation?
  5. Are there any memory limitations we need to be aware of beyond the standard integer overflow prevention and the modulo operation?

Brute Force Solution

Approach

The width of any subsequence is determined solely by its maximum and minimum elements, so the original order of elements does not matter. After sorting the array, each element acts as the maximum in a fixed number of subsequences and as the minimum in another fixed number of subsequences. By precomputing powers of two, we can calculate each element's total contribution to the answer in linear time.

Here's how the algorithm would work step-by-step:

  1. Sort the input list in non-decreasing order.
  2. Precompute powers of two up to the length of the list modulo 10^9 + 7.
  3. Iterate through each element, computing how many subsequences it serves as the maximum element for.
  4. Compute how many subsequences the same element serves as the minimum element for.
  5. Multiply the element value by the difference between its maximum and minimum counts.
  6. Sum these values modulo 10^9 + 7 and return the total result.

Code Implementation

def sum_subseq_widths(nums):
    # Sort the array so that every element's rank is known
    nums.sort()
    modulo = 10**9 + 7
    total_width = 0
    length = len(nums)
    # Precompute powers of two modulo 10^9 + 7
    powers_of_two = [1] * length
    for index in range(1, length):
        powers_of_two[index] = (powers_of_two[index - 1] * 2) % modulo
    # Accumulate contributions of each element as maximum and minimum
    for index in range(length):
        max_contributions = powers_of_two[index]
        min_contributions = powers_of_two[length - 1 - index]
        element_contribution = (max_contributions - min_contributions) * nums[index]
        total_width = (total_width + element_contribution) % modulo
    return total_width

Big(O) Analysis

Time Complexity
O(n log n) – Sorting the array of size n takes O(n log n) time, followed by a linear scan of O(n) to precompute powers of two and accumulate the total width.
Space Complexity
O(n) – An array of size n is used to store precomputed powers of two modulo 10^9 + 7.

Optimal Solution

Approach

The width of any subsequence depends solely on its maximum and minimum values, which are invariant to the order of elements. By sorting the array, each element's contribution as a maximum and as a minimum can be calculated based on the number of elements smaller and larger than it. We can then compute the sum of all widths in a single linear pass using precomputed or on-the-fly powers of two.

Here's how the algorithm would work step-by-step:

  1. Sort the input list in non-decreasing order so order statistics can be computed directly from indices.
  2. Initialize the modulo constant and an accumulator for the total sum of widths.
  3. Iterate through the array while maintaining the current power of two corresponding to subset counts.
  4. Add the contribution of the element as the maximum and subtract its contribution as the minimum.
  5. Return the resulting total width constrained within the modulo.

Code Implementation

def sum_subseq_widths(nums: list[int]) -> int:
    # Sort the array to easily determine min and max contributions.
    nums.sort()
    modulo = 1_000_000_007
    total_width = 0
    current_power = 1
    length = len(nums)
    # Accumulate contributions where each element acts as a maximum and minimum.
    for index in range(length):
        total_width = (total_width + nums[index] * current_power - nums[length - 1 - index] * current_power) % modulo
        # Update powers of two for the next pair of elements.
        current_power = (current_power * 2) % modulo
    # Return the final aggregated width modulo 10^9 + 7.
    return (total_width + modulo) % modulo

Big(O) Analysis

Time Complexity
O(n log n) – Sorting the array of size n dominates the runtime with O(n log n) time, followed by a linear O(n) pass to compute the widths.
Space Complexity
O(1) – The algorithm sorts the array in-place or uses O(n) depending on the Python sort implementation, requiring only O(1) additional auxiliary variables.

Edge Cases

Array with a single element
How to Handle:
Return zero because a subsequence of size one has a width of zero since the maximum and minimum are the same.
Array with only two elements
How to Handle:
Compute the absolute difference between the two sorted elements and return it as the only subsequence width.
Array with all identical elements
How to Handle:
Return zero because every subsequence will have equal maximum and minimum values, resulting in a width of zero.
Array containing negative numbers and mixed signs
How to Handle:
Sort the array in ascending order so that relative magnitudes are correctly established for width calculations regardless of sign.
Maximum constraint array size up to 100,000 elements
How to Handle:
Use an O(N log N) sorting approach with precomputed powers of two to ensure the solution executes well within time limits.
Result exceeding standard integer limits and requiring modulo arithmetic
How to Handle:
Apply modulo 10^9 + 7 at each addition and multiplication step using 64-bit integers to prevent arithmetic overflow.
Array with duplicate values
How to Handle:
Sorting groups duplicates adjacent to each other, and the mathematical positional contribution formula correctly accounts for identical values.
0/9 completed