Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

891. Sum of Subsequence Widths

ArrayMathSorting

Explanation

To solve this problem, we need to find the width of all possible subsequences of the given array and sum up these widths. The width of a subsequence is the difference between the maximum and minimum elements in that subsequence. We can achieve this by sorting the array and then calculating the contribution of each element to the sum.

  1. Sort the array nums.
  2. For each element num[i] in nums, calculate its contribution to the sum.
  3. The contribution of num[i] is (2^i - 2^(n-1-i)) * num[i], where i is the index of the element in the sorted array and n is the length of the array.
  4. Sum up the contributions for all elements and return the result modulo 10^9 + 7.

Time complexity: O(nlogn) where n is the length of the input array. Space complexity: O(1)

class Solution {
    public int sumSubseqWidths(int[] nums) {
        int mod = 1000000007;
        Arrays.sort(nums);
        int n = nums.length;
        long sum = 0;
        long pow2 = 1;
        
        for (int i = 0; i < n; i++) {
            sum = (sum + (pow2 - pow(2, n - 1 - i)) * nums[i]) % mod;
            pow2 = (pow2 * 2) % mod;
        }
        
        return (int)sum;
    }
    
    private long pow(int x, int n) {
        if (n == 0) return 1;
        long mod = 1000000007;
        long res = 1;
        long base = x;
        while (n > 0) {
            if (n % 2 == 1) {
                res = (res * base) % mod;
            }
            base = (base * base) % mod;
            n /= 2;
        }
        return res;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.