875885. Bits Counting

Medium

Bits Counting

Summary

The Bits Counting problem is a medium-level algorithmic challenge that involves counting the number of bits set in an array of integers. This problem requires a good understanding of bit manipulation and dynamic programming concepts.

Detailed Explanation

Given an array of integers, we need to count the total number of bits set (i.e., 1's) in all the numbers of the array. For example, if the input array is [5, 3, 10, 6], the output should be 7 because there are 2 bits set in 5 (101), 1 bit set in 3 (11), 2 bits set in 10 (1010), and 1 bit set in 6 (110). So, the total number of bits set is 2 + 1 + 2 + 1 = 7.

To solve this problem, we can use a dynamic programming approach. Initialize an array dp of size 32, where each element dp[i] represents the count of numbers in the input array that have at least one bit set at position i. Then, iterate over each number in the input array and update the dp array accordingly.

Here's a step-by-step breakdown of the solution:

  1. Initialize an array dp of size 32 with all elements set to 0.
  2. Iterate over each number num in the input array:
    • Convert num to binary and iterate over its bits from right to left (i.e., from least significant bit to most significant bit).
    • For each bit that is set, increment the corresponding element in dp.
  3. The final answer is the sum of all elements in dp.

Time complexity: O(n), where n is the size of the input array. Space complexity: O(1) since we are only using a fixed-size array dp of size 32.

Here's an ASCII art diagram illustrating the bit manipulation process:

  num = 5 (binary: 101)
    |
    +-- dp[0] = 0 (no bits set at position 0)
    |    dp[1] = 1 (one bit set at position 1)
    |     ...
    |    dp[2] = 0
    |     dp[3] = 1

  num = 3 (binary: 11)
    |
    +-- dp[0] = 0
    |    dp[1] = 2 (two bits set at position 1)
    |     ...
    |    dp[2] = 0
    |     dp[3] = 0

  num = 10 (binary: 1010)
    |
    +-- dp[0] = 0
    |    dp[1] = 1
    |     dp[2] = 1
    |      ...
    |     dp[3] = 0

  num = 6 (binary: 110)
    |
    +-- dp[0] = 0
    |    dp[1] = 1
    |     dp[2] = 1
    |      ...

  Final answer = dp[0] + dp[1] + ... + dp[31]

Optimized Solutions

Java

View on GeeksforGeeks
public int bitsCounting(int[] arr) {
    int n = arr.length;
    int[] dp = new int[32];
    for (int num : arr) {
        for (int i = 0; i < 32; i++) {
            if (((num >> i) & 1) == 1) {
                dp[i]++;
            }
        }
    }
    int ans = 0;
    for (int i = 0; i < 32; i++) {
        ans += dp[i];
    }
    return ans;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.