Subsets I

Recursion FAQs (Medium) Medium
  • This problem is actually a fundamental concept in business analytics and Big Data processing
  • Whenever companies perform market basket analysis (eg supermarket transaction data to find the association between different item sets) or power set calculations, this function for calculating the sum of all subsets can be heavily used
  • Having optimized algorithms to solve this problem can greatly improve the efficiency of processing large datasets
  • This subset sum problem is also related to cryptography, operations research, and complexity theory, all essential concepts in software industry

Given an array nums of n integers.Return sum of all subsets of the array nums.


Output can be printed in any order.

Examples:

Input : nums = [2, 3]

Output : [0, 2, 3, 5]

Explanation :

When no elements is taken then Sum = 0.

When only 2 is taken then Sum = 2.

When only 3 is taken then Sum = 3.

When element 2 and 3 are taken then sum = 2+3 = 5.

Input : nums = [5, 2, 1]

Output : [0, 1, 2, 3, 5, 6, 7, 8]

Explanation :

When no elements is taken then Sum = 0.

When only 5 is taken then Sum = 5.

When only 2 is taken then Sum = 2.

When only 1 is taken then Sum = 1.

When element 2 and 1 are taken then sum = 2+1 = 3.

Input : nums = [1]

Constraints

  • 1 <= n <= 15
  • 0 <= nums[i] <= 104

Hints

  • "Each element in nums contributes to exactly half of the subsets because every element either appears or doesn't appear in any given subset. For an element x in nums, it contributes x×2^n−1 to the total sum, where n is the size of the array."
  • Generate all subsets of nums and compute their sums individually.

Company Tags

Docker Bloomberg Texas Instruments Seagate Technology Red Hat Bungie Epic Games Zomato Splunk Walmart Wayfair Cloudflare Boston Consulting Group HashiCorp Ubisoft Robinhood Snowflake Ernst & Young Rakuten Optum Instacart Unity Technologies Flipkart Teladoc Health Uber Google Microsoft Amazon Meta Apple Netflix Adobe