Python 1680.py
class Solution:
def concatenatedBinary(self, n: int) -> int:
result = 0
shift = 0
for i in range(1, n+1):
# exactly one bit set => bit representation just got longer
if i & (i-1) == 0:
shift += 1
result <<= shift
result += i
# avoiding large numbers which slow down the program
result %= 10**9 + 7
return result
Difficulty
and has an acceptance rate of about 67% (200k+ submissions).
Typical patterns to solve this problem:
- Bit Manipulation
- Math
- Simulation
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the integer formed by concatenating the binary representations of all numbers from 1 to n, then returns the result modulo 10⁹ + 7. The algorithm proceeds in a single forward pass, maintaining a running value that is progressively shifted and extended with each successive integer. By updating the shift width only when the binary length of the current integer increases, the code avoids recomputing the bit-length repeatedly. A modular reduction after each iteration prevents the intermediate value from growing beyond the range of native integer arithmetic, which keeps the execution fast even for large inputs.
Key Steps
Detecting a change in binary length
The binary length of a positive integer grows exactly when the integer is a power of two. The code uses a classic bit-wise test to identify such numbers:
if i & (i-1) == 0:
shift += 1
When i has only a single set bit, the expression i & (i-1) evaluates to zero, signalling that the next integer will require one more bit in its binary representation. The variable shift therefore tracks the current width of the binary block that must be appended.
Shifting the accumulated result
Before appending the new integer, the accumulated result is left-shifted by the current shift value:
result <<= shift
A left shift by k positions is equivalent to multiplying by 2ᵏ, which aligns the existing bits to make room for the next binary block. Because shift is updated only when the binary length changes, the shift amount is always the exact number of bits needed for the new integer.
Adding the current integer
After creating space, the current integer i is added directly to the shifted result:
result += i
Since i already occupies exactly shift bits, this operation effectively concatenates its binary representation onto the tail of the accumulated binary string.
Applying the modular reduction
To keep the intermediate value within a manageable range, the code reduces the result modulo the prime 10**9 + 7 after each iteration:
result %= 10**9 + 7
This step prevents the integer from expanding to an unwieldy size, which would otherwise slow down arithmetic operations due to Python’s arbitrary-precision integers. By performing the reduction at every step, the algorithm ensures that each intermediate value stays bounded, leading to consistent performance.
Returning the final value
When the loop finishes, the variable result already contains the required concatenated binary number reduced modulo the given constant, and it is returned directly:
return result
Edge Cases Handled
When n is zero, the for loop does not execute because the range 1 to n+1 is empty. Consequently, result remains at its initial value of 0, and the function returns 0. This behavior correctly represents the concatenation of an empty sequence of binary numbers.
The power-of-two detection works for the smallest power, 1, because 1 & 0 equals 0. The shift variable is therefore incremented from its initial value of 0 to 1 before the first concatenation, ensuring that the first binary digit is placed correctly.
Because the modular reduction is applied after each addition, the function safely handles the maximum possible intermediate value that could arise from concatenating up to the largest supported n. The reduction guarantees that overflow never occurs, even when the concatenated binary string would otherwise exceed the limits of typical fixed-size integer types.
Performance Optimizations
The algorithm avoids recomputing the bit length of each integer by maintaining a running shift counter that only changes when a power of two is encountered. This eliminates the need for costly logarithmic or string-based length calculations.
Using the left-shift operator (<<=) to create space for the new bits is more efficient than multiplying by a power of two, as the operation maps directly to low-level bit manipulation instructions.
The modular reduction is performed inside the loop rather than only at the end. By keeping the intermediate result bounded, the code prevents Python’s arbitrary-precision integer implementation from allocating increasingly larger memory blocks, which would degrade speed for large n. This incremental reduction thus preserves a tight execution profile throughout the entire iteration.
ELI5 - Simplified Explanation
Imagine a little robot that loves to collect numbers. This robot wants to build a giant string of special numbers made of only zeros and ones. Think of this like building a long tower out of blocks. The code starts with an empty space and gets ready to stack numbers one by one, from one up to the number that was chosen.
Every time the robot goes to pick up the next number, it checks if the number is a special power of two. When that happens, the length of the binary string gets a little bit longer, so the robot makes sure to remember that extra space.
Then, the robot takes the long chain of numbers it has built so far and pushes everything over to the left to make room for the new number. This is like sliding your toys to the side so you can put a new toy on your shelf. Once the shelf has space, the new number is added to the end.
Because the building can get super tall and messy if the numbers grow too big, the robot performs a trick to keep the number manageable by dividing it and keeping only the remainder. This keeps the tower tidy while the robot finishes adding every number in the line. After all the numbers have been added and sorted into the right spot, the big chain is complete.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Python | JS | Go | C# | Rust | TS | |
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ | ||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 680: Valid Palindrome II
- problem 478: Generate Random Point in a Circle
- problem 497: Random Point in Non-overlapping Rectangles
- problem 519: Random Flip Matrix
- problem 581: Shortest Unsorted Continuous Subarray
- problem 659: Split Array into Consecutive Subsequences
- problem 738: Monotone Increasing Digits
- problem 743: Network Delay Time
- problem 769: Max Chunks To Make Sorted
- problem 985: Sum of Even Numbers After Queries
- problem 1048: Longest String Chain
- problem 1094: Car Pooling
- problem 1324: Print Words Vertically
- problem 1823: Find the Winner of the Circular Game
- problem 1860: Incremental Memory Leak
- problem 1922: Count Good Numbers
- problem 2487: Remove Nodes From Linked List
- problem 381: Insert Delete GetRandom O(1) - Duplicates allowed
- problem 517: Super Washing Machines
- problem 632: Smallest Range Covering Elements from K Lists
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality