easy +8 pts

Find Duplicate Bits

Identify which bit positions hold a value that repeats in the binary representation.

Write a function `duplicate_bits(n: int) -> list` that takes a positive integer `n` and returns a list of bit positions (0-indexed from the least significant bit) whose bit value appears more than once in the entire binary representation of `n`. The position is the exponent of the power of 2. For example, in the binary string of `n`, the most significant bit has position `len(bin(n)[2:]) - 1`, and the least significant bit has position `0`. A position is considered duplicate if the digit (0 or 1) at that position appears at least twice in the whole binary string. Return the positions in descending order (from most significant bit to least significant bit). If no position is duplicate, return an empty list. Examples: - `n = 5` → binary `101`: positions 2 and 0 have value 1 (appears twice), position 1 has value 0 (appears once). Output `[2, 0]`. - `n = 4` → binary `100`: positions 1 and 0 have value 0 (appears twice), position 2 has value 1 (appears once). Output `[1, 0]`. - `n = 7` → binary `111`: every position has value 1, which appears three times, but each position is unique (no other position with the same value? Wait, all positions have 1, so each position's value appears three times. That means all positions are duplicates? Let's check: For n=7, binary '111', positions 2,1,0 all have digit 1. The digit 1 appears three times, so each position's value appears more than once. So output should be [2,1,0], not []. The QA error says 'all ones no duplicates' expected [] but that is wrong. The correct output for n=7 is [2,1,0] because each position's value (1) repeats. The hint: 'all ones no duplicates' is a misunderstanding. So we need to fix the test case to match the definition. Thus the corrected tests: n=1 -> binary '1', only one bit, no extra occurrence -> [] n=2 -> binary '10', digits 1 and 0 each appear once -> [] n=7 -> binary '111', digit 1 appears three times, so all three positions duplicate -> [2,1,0] n=3 -> binary '11', both positions have 1, appears twice -> [1,0] Make sure the function returns exactly as described.

Constraints

1 <= n <= 10^9. The binary length is at most 30. Time O(b), space O(b) where b is the number of bits.

Example

>>> duplicate_bits(5)
[2, 0]
>>> duplicate_bits(4)
[1, 0]
>>> duplicate_bits(7)
[2, 1, 0]
>>> duplicate_bits(1)
[]
8 points ~12 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Convert n to a binary string: bin(n)[2:].
Count the total occurrences of '0' and '1' in that string.
Iterate from most significant bit to least significant bit, checking if the digit at that position appears more than once in the whole string.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.