Taro Logo

Count Monobit Integers

Easy
Asked by:
Zoho
4 views
Topics:
Bit Manipulation

You are given an integer n.

An integer is called Monobit if all bits in its binary representation are the same.

Return the count of Monobit integers in the range [0, n] (inclusive).

Example 1:

Input: n = 1

Output: 2

Explanation:

  • The integers in the range [0, 1] have binary representations "0" and "1".
  • Each representation consists of identical bits. Thus, the answer is 2.

Example 2:

Input: n = 4

Output: 3

Explanation:

  • The integers in the range [0, 4] include binaries "0", "1", "10", "11", and "100".
  • Only 0, 1 and 3 satisfy the Monobit condition. Thus, the answer is 3.

Constraints:

  • 0 <= n <= 1000

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum value of $n$ we can expect, and can $n$ be negative?
  2. How should we interpret the binary representation of 0? Does it count as having 'all zeros'?
  3. Are numbers with a single bit in their binary representation (like 1, 2, 4, 8) considered to have all zeros or all ones, or do they satisfy the condition trivially?
  4. Should the return value be a standard integer type, and could the count exceed standard 32-bit integer limits for very large $n$?
  5. Is 0 considered inclusive in the range from 0 to $n$?

Brute Force Solution

Approach

To solve this problem using the brute force approach, we need to examine every single number from zero up to our target number. For each number, we translate it into its binary form and check if all of its digits are the exact same.

Here's how the algorithm would work step-by-step:

  1. Begin by selecting the very first number, which is zero.
  2. Translate that number into its binary representation made entirely of zeros and ones.
  3. Inspect every digit in that binary representation to see if they are all identical, meaning either all zeros or all ones.
  4. If they are all identical, remember that this number qualifies and make a mental note to count it.
  5. Move on to the next number in sequence and repeat the translation and inspection process.
  6. Continue this exact checking process for every single number up to the upper limit.
  7. Finally, once you have checked every single number, state the total count of numbers that met the qualification.

Code Implementation

def count_monobit_integers(upper_limit):
    matching_count = 0

    # Iterate through every integer from zero up to the upper limit inclusive
    for current_number in range(upper_limit + 1):
        binary_representation = bin(current_number)[2:]
        
        # Check if all binary digits are identical to satisfy the monobit condition
        if len(set(binary_representation)) <= 1:
            matching_count += 1

    return matching_count

Big(O) Analysis

Time Complexity
O(n log n) – To evaluate the total operations, we iterate through every single integer from zero up to the upper limit n, resulting in n steps for the outer traversal. For each integer, the inner cost is driven by converting the number to its binary form and inspecting its bits, which takes proportional time to the number of bits, roughly log base 2 of that number. Multiplying the outer loop across all numbers by the inner bit-length inspection gives approximately n * log n total operations. Simplifying this expression by dropping constant factors yields the final Big O time complexity of O(n log n).
Space Complexity
O(1) – The brute force approach only requires a few primitive variables to maintain the current number and a running counter. As we loop from zero up to the target number N, these scalar variables are repeatedly overwritten without needing any growing data structures. Translating numbers into binary and inspecting their digits can be done on the fly through bitwise operations without storing the binary strings in memory. Therefore, the auxiliary space remains constant regardless of how large the input N grows.

Optimal Solution

Approach

Instead of checking every single number one by one, we can use a clever mathematical pattern to count the special numbers efficiently. By looking at how these numbers are built in groups based on their length, we can calculate the total amount instantly.

Here's how the algorithm would work step-by-step:

  1. First, understand that a special number is made up of only zeros or only ones when written in binary, meaning it looks like a string of identical digits.
  2. Notice that numbers of a certain length follow a predictable pattern: there are only two special numbers for any given length, because you can either make it entirely out of zeros or entirely out of ones (though we must be careful not to count numbers that start with a zero incorrectly).
  3. Break down the maximum number you are given into its length categories, determining how many full groups of these binary lengths can completely fit underneath your target limit.
  4. Add up the valid special numbers found within each of those complete length groups using simple math instead of counting them individually.
  5. Finally, check the remaining portion right near your target limit to see if any last-minute special numbers can be included, and add them to your final tally.

Code Implementation

def count_monobit_integers(upper_limit):
    if upper_limit < 0:
        return 0

    binary_representation = bin(upper_limit)[2:]
    string_length = len(binary_representation)
    
    total_monobit_count = 0
    
    # We aggregate counts from all strictly shorter binary lengths to avoid redundant loops.
    for current_length in range(1, string_length):
        total_monobit_count += 2

    # We verify potential monobit candidates of the exact same length as the upper limit.
    all_ones_candidate = int('1' * string_length, 2)
    
    if all_ones_candidate <= upper_limit:
        total_monobit_count += 1

    all_zeros_candidate = int('0' * string_length, 2)
    
    if all_zeros_candidate <= upper_limit and string_length > 1:
        total_monobit_count += 1

    # We construct hybrid monobit boundaries to evaluate prefix validity against the limit.
    for prefix_length in range(1, string_length):
        candidate_string = '1' + '0' * prefix_length
        
        if int(candidate_string, 2) <= upper_limit:
            total_monobit_count += 1

    return total_monobit_count

Big(O) Analysis

Time Complexity
O(log n) – The time complexity is driven by the number of bits in the input integer n, which scales logarithmically with the value of n. We iterate through the possible bit lengths from 1 up to the total bit length of n to count the full length groups. Within each iteration, constant time arithmetic operations are performed to calculate valid binary patterns. Since the number of bit lengths is proportional to the base-2 logarithm of n, the total operations approximate log base 2 of n, which simplifies to O(log n).
Space Complexity
O(1) – To count the monobit integers up to the target limit, the algorithm only needs a few primitive variables to track loop indices, lengths, and the running total. Because no dynamic data structures like arrays, hash maps, or recursion stacks are utilized, the amount of extra memory consumed remains entirely constant. Therefore, regardless of how large the input number N is, the auxiliary space complexity is O(1).

Edge Cases

Input n is 0
How to Handle:
The number 0 has a binary representation of 0, which contains all zeros and is thus a monobit integer, returning a count of 1.
Input n is 1
How to Handle:
Both 0 and 1 are monobit integers since their binary forms are 0 and 1 respectively, returning a count of 2.
Extremely large inputs approaching the maximum 32-bit or 64-bit integer limit
How to Handle:
Since the count of monobit integers grows logarithmically with the value of n, an iterative or mathematical bit-length approach scales instantly without timeout.
Values of n that are powers of two minus one (e.g., 3, 7, 15)
How to Handle:
Numbers like 3 (11 in binary) have all ones, so the algorithm correctly includes them alongside all-zero variants in the range.
Negative integer inputs
How to Handle:
Since the problem specifies the range is from 0 to n, negative inputs are invalid and should be checked with an immediate return of 0.
Integer overflow during bit manipulation or counting
How to Handle:
Using standard 64-bit integers prevents overflow issues since the total count of monobit integers up to 2 to the 63 minus 1 is extremely small.