Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! π»π₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! π
100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney
Problem:
https://www.geeksforgeeks.org/problems/sum-of-xor-of-all-possible-subsets/1
All Subsets Xor Sum
Difficulty: Medium Accuracy: 66.8%
Given an array arr[], return the sum of the XOR of all elements for every possible subset of the array. Subsets with the same elements should be counted multiple times.
An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b.
Note: The answer is guaranteed to fit within a 32-bit integer.
Examples:
Input: arr[] = [7, 2]
Output: 14
Explanation: Subsets are: [[], [7], [2], [7, 2]]
Sum of all XOR's = 7 + 2 + (7 ^ 2) = 14.
Input: arr[] = [1, 2, 3]
Output: 12
Explanation: Subsets are: [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
Sum of all XOR's = 1 + 2 + 3 + (1 ^ 2) + (1 ^ 3) + (2 ^ 3) + (1 ^ 2 ^ 3) = 12.
Constraints:
1 β€ arr.size() β€ 30
1 β€ arr[i] β€ 103
Solution:
class Solution:
def subsetXORSum(self, arr):
ors = 0
for x in arr:
ors |= x
return ors * (1 << (len(arr) - 1))
Top comments (0)