Leetcode 338: Counting Bits

grid47
grid47
Exploring patterns and algorithms
Oct 4, 2024 4 min read

A glowing sequence of numbers where each bit is counted and highlighted as part of the total.
Solution to LeetCode 338: Counting Bits Problem

Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1’s in the binary representation of i.
Problem
Approach
Steps
Complexity
Input: You are given an integer n.
Example: n = 3
Constraints:
• 0 <= n <= 10^5
Output: Return an array ans such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.
Example: [0, 1, 1, 2]
Constraints:
• The solution must run in linear time O(n).
Goal: Calculate the number of 1's in the binary representation for each number from 0 to n.
Steps:
• Initialize an array res of size n + 1 with 0s.
• For each number i from 0 to n, set res[i] = res[i >> 1] + (i & 1).
• Return the array res.
Goal: The solution must be efficient with O(n) time complexity and without using any built-in popcount functions.
Steps:
• The solution must run efficiently for n values as large as 10^5.
Assumptions:
• The value of n is within the given constraints.
Input: n = 3
Explanation: For the input n = 3, the binary representations of 0, 1, 2, and 3 are '0', '1', '10', '11'. The number of 1's in these binary numbers are 0, 1, 1, and 2 respectively.

Input: n = 6
Explanation: For the input n = 6, the binary representations of 0, 1, 2, 3, 4, 5, and 6 are '0', '1', '10', '11', '100', '101', '110'. The number of 1's in these binary numbers are 0, 1, 1, 2, 1, 2, and 2 respectively.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus