338. Counting Bits

Counting Bits (LeetCode 338) is a Easy Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Bit Manipulation Patterns pattern, in the Bitwise DP - Counting Bits Optimization subpattern.

How to solve Counting Bits

Counting Bits is a Counting Bits with DP problem, part of Bit Manipulation Patterns. Count bits for range of numbers using DP with bit manipulation optimization.

Work towards the solution in these steps:

  1. You should make use of what you have produced already.
  2. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
  3. Or does the odd/even status of the number help you in calculating the number of 1s?

The reference solution runs in O(n) time and O(n) space.

The Counting Bits solution and editorial walks through the full approach with reference code.

Problem statement

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.

Example 1:

Input: n = 2 Output: [0,1,1] Explanation: 0 --> 0 1 --> 1 2 --> 10

Example 2:

Input: n = 5 Output: [0,1,1,2,1,2] Explanation: 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101

Constraints:

- 0 <= n <= 10^5

Follow up:

- It is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass?

- Can you do it without using any built-in function (i.e., like builtinpopcount in C++)?

Topics and companies

Topics: Dynamic Programming, Bit Manipulation.

Reported in interviews at Amazon, Blizzard.

How to practise Counting Bits on Thita.ai

Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(n) time and O(n) space.

Open Counting Bits in the code editor, or read the Counting Bits editorial for a worked solution with its approach and complexity analysis.

Where Counting Bits sits in the DSA pattern sheet

Problems related to Counting Bits

Other problems that use the same Bitwise DP - Counting Bits Optimization and Bit Manipulation Patterns techniques:

Counting Bits FAQ

What is the LeetCode number of Counting Bits?

Counting Bits is LeetCode problem 338, rated Easy.

What pattern is used to solve Counting Bits?

Counting Bits is a Counting Bits with DP problem. It belongs to the Bit Manipulation Patterns pattern, in the Bitwise DP - Counting Bits Optimization subpattern.

What is the time complexity of Counting Bits?

The reference solution runs in O(n) time and O(n) space.

Which companies ask Counting Bits?

Counting Bits has been reported in interviews at Amazon, Blizzard.

Preparing this workspace.