Published 2024-05-17

0338. Counting Bits

leetcode

Problem Overview

The problem "Counting Bits" requires us to return an array `ans` where `ans[i]` is the number of 1's in the binary representation of the number `i` for all `i` in the range 0 to `n` inclusive.

Key Points:

  • We need to count the number of 1's in the binary representation of numbers from 0 to `n`.
  • The result should be stored in an array.

Solution Outline

  1. Preferred Structure:
    • Use an array to store the count of 1's for each number from 0 to `n`.
  2. Brute Force vs Optimal Solution:
    • Brute Force: For each number, convert it to its binary form and count the 1's. This would be inefficient.
    • Optimal Solution: Utilize a dynamic programming approach where the count of 1's for a number can be derived from previously computed results. Specifically, use the relation: `countBits[i] = countBits[i >> 1] + (i & 1)`.
  3. Algorithm Choice:
    • Dynamic Programming: This approach leverages previously computed results to build up the solution efficiently.

Implementation Plan

  1. Initialize an array `result` of length `n + 1` with all elements set to 0.
  2. Iterate from 1 to `n`, updating each entry based on the relation `result[i] = result[i >> 1] + (i & 1)`.
/**
 * Function to count the number of 1's in the binary representation of numbers from 0 to n.
 * @param {number} n - The upper limit of the range.
 * @returns {number[]} - Array where the ith element is the number of 1's in the binary representation of i.
 */
function countBits(n) {
    // Initialize the result array with zeros
    const result = Array(n + 1).fill(0);

    for (let i = 0; i < result.length; i++) {
        let el = i;
        let cnt = el & 1;
        el = el >> 1;

        while (el > 0) {
            cnt += el & 1;
            el = el >> 1;
        }
        result[i] = cnt;

    }
    return result;
}

// Test cases
const testCases = [
    { n: 2, expected: [0, 1, 1] },
    { n: 5, expected: [0, 1, 1, 2, 1, 2] },
    // Additional test cases
    { n: 0, expected: [0] },
    { n: 1, expected: [0, 1] },
    { n: 10, expected: [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2] },
];

testCases.forEach((test, index) => {
    const result = countBits(test.n);
    console.log(`Test Case ${index + 1}: ${JSON.stringify(result) === JSON.stringify(test.expected) ? 'Passed' : 'Failed'} (Expected: ${JSON.stringify(test.expected)}, Got: ${JSON.stringify(result)})`);
});

Solution Analysis

  • Time Complexity: O(n). Each number from 0 to `n` is processed exactly once.
  • Space Complexity: O(n). We use an array of size `n + 1` to store the result.
© d)zharii. sitemap