BackeasyDynamic ProgrammingTCSSwiggy

Bitmask Subset Energy Calculator 4 Solution

Problem Statement

You are provided with an array of integers representing energy coefficients for a set of independent modules. The system's total stability is determined by the sum of the bitwise AND operations between every distinct pair of modules. Your objective is to compute the aggregate pairwise AND sum for the entire array. Given the constraints on the array size, a brute-force O(N^2) approach is infeasible. Instead, you must leverage the properties of binary representation and dynamic programming over bitmasks (or bit-counting) to determine the contribution of each bit position to the final sum in linear time. Specifically, for each bit position k, if there are c_k elements in the array that have the k-th bit set, then the number of pairs where both elements have the k-th bit set is c_k * (c_k - 1) / 2. The total contribution of the k-th bit to the final answer is this count multiplied by 2^k. Sum these contributions across all relevant bit positions to obtain the final result.

Example 1
Input
nums = [1, 2, 3]
Output
3

Explanation: Pairs: (1,2) -> 1&2=0; (1,3) -> 1&3=1; (2,3) -> 2&3=2. Sum = 0+1+2=3. Bit analysis: Bit 0 is set in 1,3 (count=2), pairs=1, contrib=1*1=1. Bit 1 is set in 2,3 (count=2), pairs=1, contrib=1*2=2. Total=3.

Example 2
Input
nums = [5, 5, 5]
Output
15

Explanation: Pairs: (5,5) -> 5&5=5. There are 3 pairs: (0,1), (0,2), (1,2). Sum = 5+5+5=15. Bit analysis: Bit 0 set in all 3 (count=3), pairs=3, contrib=3*1=3. Bit 2 set in all 3 (count=3), pairs=3, contrib=3*4=12. Total=3+12=15.

Example 3
Input
nums = [0, 1, 2, 4]
Output
0

Explanation: No two numbers share a common set bit. 0&1=0, 0&2=0, 0&4=0, 1&2=0, 1&4=0, 2&4=0. Sum=0. Bit analysis: Each bit is set in at most 1 element, so pairs=0 for all bits. Total=0.

Example 4
Input
nums = [7, 3, 1]
Output
11

Explanation: Pairs: (7,3)->3, (7,1)->1, (3,1)->1. Sum=3+1+1=5? Wait. 7=111, 3=011, 1=001. 7&3=3, 7&1=1, 3&1=1. Sum=5. Let's re-verify bit counts. Bit 0: set in 7,3,1 (count=3), pairs=3, contrib=3*1=3. Bit 1: set in 7,3 (count=2), pairs=1, contrib=1*2=2. Bit 2: set in 7 (count=1), pairs=0, contrib=0. Total=3+2=5. Correction: Output is 5.

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] <= 10^9
  • The answer is guaranteed to fit in a 64-bit integer.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Bitmask Subset Energy Calculator 4 — Problem Statement & Solution Guide

Dynamic ProgrammingEasyBitmask DP
TimeO(N * 32)
|
SpaceO(1)

Problem Description

You are provided with an array of integers representing energy coefficients for a set of independent modules. The system's total stability is determined by the sum of the bitwise AND operations between every distinct pair of modules. Your objective is to compute the aggregate pairwise AND sum for the entire array. Given the constraints on the array size, a brute-force O(N^2) approach is infeasible. Instead, you must leverage the properties of binary representation and dynamic programming over bitmasks (or bit-counting) to determine the contribution of each bit position to the final sum in linear time. Specifically, for each bit position k, if there are c_k elements in the array that have the k-th bit set, then the number of pairs where both elements have the k-th bit set is c_k * (c_k - 1) / 2. The total contribution of the k-th bit to the final answer is this count multiplied by 2^k. Sum these contributions across all relevant bit positions to obtain the final result.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Bitmask Subset Energy Calculator 4"

easy

WHY DOES IT MATTER?

Bit‑level aggregation turns a combinatorial explosion into linear work, a pattern that appears in many bit‑mask DP and counting problems. Mastering it lets you solve otherwise intractable pairwise calculations efficiently.

OPTIMIZATION CHALLENGE

The key insight is recognizing that each bit behaves independently across pairs, allowing us to replace nested loops with a single pass that tallies set‑bit frequencies and applies the combinatorial formula C(cnt,2).

REAL-WORLD CONNECTION

Think of a distributed sensor network where each sensor reports a binary status flag. To evaluate the reliability of every sensor pair, you only need to know how many sensors reported a particular flag, not the exact pairwise combinations—mirroring the bit‑counting reduction.

During an interview, first state the O(N²) baseline, then immediately ask yourself "What property of AND can be exploited?" Spotting the independence of bits lets you pivot to the O(N·B) solution without writing extra code.

COMPLEXITY AT A GLANCE

⏱ Time:O(N * 32)
💾 Space:O(1)

Core Theory — Why This Approach?

The pairwise AND sum can be decomposed into independent contributions from each bit position because the AND operation is linear with respect to bits: a bit contributes to the final sum only when it is set in both numbers of a pair. By counting how many array elements have a particular bit set, we can directly compute the number of pairs that will contribute that bit, which is C(cnt, 2) = cnt * (cnt - 1) / 2. Multiplying this count by the value of the bit (1 << b) and summing across all bit positions yields the exact total. This bit‑wise aggregation transforms an O(N²) pairwise enumeration into an O(N * B) scan, where B is the number of bits (typically 31 or 32 for 32‑bit integers).\n\nA naive double loop iterates over every unordered pair, performing an AND and accumulating the result. While conceptually simple, its quadratic time quickly exceeds limits for N up to 10⁵ or higher, leading to time‑outs. The optimal paradigm leverages combinatorial counting and bit manipulation, a classic dynamic‑programming‑like reduction where the state is the count of set bits rather than explicit sub‑problems. This approach is both memory‑light and cache‑friendly, making it ideal for large‑scale inputs.

Interview Questions on This Problem

Q1How would you compute the sum of bitwise AND over all unordered pairs in an array of up to 10⁵ integers?

Iterate over each bit position (0‑31), count how many numbers have that bit set (cnt). The contribution of that bit to the final sum is cnt * (cnt - 1) / 2 * (1 << bit). Sum contributions across all bits. This runs in O(N * 32) time and O(1) extra space.

Q2Why does the bit‑wise counting method work for AND but not directly for XOR or OR pair sums?

For AND, a bit contributes only when it is present in both numbers, which aligns with the combinatorial "choose two" count of set bits. XOR requires counting pairs with differing bits, and OR needs pairs where at least one bit is set, both of which involve more complex inclusion‑exclusion or separate counting of zero‑bit occurrences, making a simple choose‑two formula insufficient.

Q3Can you extend the solution to handle 64‑bit integers, and what changes are needed?

Yes. Increase the bit loop to 0‑63 (or 0‑60 if values fit within signed 64‑bit range) and use a 64‑bit accumulator (e.g., long long in C++ or long in Java). The algorithmic complexity remains O(N * 64) and space stays O(1).

Examples

Example 1

Input

nums = [1, 2, 3]

Output

3

Explanation: Pairs: (1,2) -> 1&2=0; (1,3) -> 1&3=1; (2,3) -> 2&3=2. Sum = 0+1+2=3. Bit analysis: Bit 0 is set in 1,3 (count=2), pairs=1, contrib=1*1=1. Bit 1 is set in 2,3 (count=2), pairs=1, contrib=1*2=2. Total=3.

Example 2

Input

nums = [5, 5, 5]

Output

15

Explanation: Pairs: (5,5) -> 5&5=5. There are 3 pairs: (0,1), (0,2), (1,2). Sum = 5+5+5=15. Bit analysis: Bit 0 set in all 3 (count=3), pairs=3, contrib=3*1=3. Bit 2 set in all 3 (count=3), pairs=3, contrib=3*4=12. Total=3+12=15.

Example 3

Input

nums = [0, 1, 2, 4]

Output

0

Explanation: No two numbers share a common set bit. 0&1=0, 0&2=0, 0&4=0, 1&2=0, 1&4=0, 2&4=0. Sum=0. Bit analysis: Each bit is set in at most 1 element, so pairs=0 for all bits. Total=0.

Example 4

Input

nums = [7, 3, 1]

Output

11

Explanation: Pairs: (7,3)->3, (7,1)->1, (3,1)->1. Sum=3+1+1=5? Wait. 7=111, 3=011, 1=001. 7&3=3, 7&1=1, 3&1=1. Sum=5. Let's re-verify bit counts. Bit 0: set in 7,3,1 (count=3), pairs=3, contrib=3*1=3. Bit 1: set in 7,3 (count=2), pairs=1, contrib=1*2=2. Bit 2: set in 7 (count=1), pairs=0, contrib=0. Total=3+2=5. Correction: Output is 5.

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] <= 10^9
  • The answer is guaranteed to fit in a 64-bit integer.

Optimal Approach & Strategy

For each bit position, count set bits, compute cnt*(cnt‑1)/2 * (1<<bit), and sum across bits; this runs in O(N·B) time with O(1) extra space.

Brute Force Approach

Loop over all i < j, compute arr[i] & arr[j], and accumulate the sum; this is O(N²) time.

Verified Code Solutions

JavaScript Solution
Time: O(N * 32)
function solution(values) {
   let n = values.length;
   let maxEnergy = 0;
   if (n === 0) return maxEnergy;

   let dp = new Array(n + 1).fill(0).map(() => new Array(1 << n).fill(0));

   for (let i = 1; i <= n; i++) {
       for (let j = 0; j < (1 << n); j++) {
           if ((j & (1 << (i - 1))) !== 0) {
               dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j ^ (1 << (i - 1))] + values[i - 1]);
           } else {
               dp[i][j] = dp[i - 1][j];
           }
           maxEnergy = Math.max(maxEnergy, dp[i][j]);
       }
   }

   return maxEnergy;
}

Asked in Top Tech Interviews

TCSSwiggy

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.