Concatenation of Consecutive Binary Numbers (LeetCode 1680): Solution and Explanation
Glue the binary forms of 1 through n into one bit string and return its value modulo 10^9 + 7.
Intuition
Building the actual string is wasteful: for n = 10^5 it is well over a million characters, and its value is astronomically large.
Appending a k-bit number x to a bit string with value v is the same as shifting v left by k places and putting x in the freed low bits. In numbers, that is v * 2^k + x.
Multiplication and addition both work modulo 10^9 + 7, so the running value can be reduced after every append and never grows beyond about 2^47 before the reduction.
The only other thing to track is k, the bit length of i. It goes up by one exactly when i reaches a power of two: 1, 2, 4, 8, ...
Approach: Running value with shift and OR
- Set
result = 0andlength = 0. - For each
ifrom 1 ton: ifi & (i - 1) == 0, i is a power of two, so increaselengthby one. - Set
result = ((result << length) | i) % MOD. - Return
result.
Step-by-step example
n = 3
- Start with result = 0 and length = 0.
- i = 1 is a power of two, so length = 1. result = (0 << 1) | 1 = 1, the string "1".
- i = 2 is a power of two, so length = 2. result = (1 << 2) | 2 = 100 | 10 = 110 = 6, the string "110".
- i = 3 is not a power of two, so length stays 2. result = (6 << 2) | 3 = 11000 | 11 = 11011 = 27.
- The loop ends. Return 27.
Code: Python, Java, C++
1class Solution:
2 def concatenatedBinary(self, n: int) -> int:
3 MOD = 10**9 + 7
4 result = 0
5 length = 0
6 for i in range(1, n + 1):
7 if i & (i - 1) == 0:
8 length += 1
9 result = ((result << length) | i) % MOD
10 return result1class Solution {
2 public int concatenatedBinary(int n) {
3 final long MOD = 1000000007L;
4 long result = 0;
5 int length = 0;
6 for (int i = 1; i <= n; i++) {
7 if ((i & (i - 1)) == 0) {
8 length++;
9 }
10 result = ((result << length) | i) % MOD;
11 }
12 return (int) result;
13 }
14}1class Solution {
2public:
3 int concatenatedBinary(int n) {
4 const long long MOD = 1000000007LL;
5 long long result = 0;
6 int length = 0;
7 for (int i = 1; i <= n; i++) {
8 if ((i & (i - 1)) == 0) {
9 length++;
10 }
11 result = ((result << length) | i) % MOD;
12 }
13 return (int) result;
14 }
15};Time and space complexity
O(n)
Each number from 1 to n is appended once with a constant amount of work.
O(1)
Only result and length are stored; the string is never built.
Other approaches
Build the string, then parse (time O(n log n), space O(n log n))
Join bin(i) for every i and parse the result with a modular loop over its characters. Correct, but it stores about n log n characters for no benefit.
Bit length per number (time O(n), space O(1))
Compute the length of each i directly (i.bit_length() or 32 - numberOfLeadingZeros(i)) instead of tracking powers of two. Same complexity, slightly more work per step.
Common mistakes
- Shifting in a 32-bit int. result can be close to 10^9 and the shift can be up to 17 bits, so the intermediate value needs 64 bits.
- Using + instead of | is fine, but forgetting the modulo until the end is not: the value overflows long before the loop ends.
- Increasing the length at the wrong time. It must grow before appending the power of two itself, since 4 is 100 and already needs 3 bits.
Frequently asked questions
Why is shifting by the bit length the same as appending?
Shifting left by k multiplies by 2^k, which adds k zero bits at the low end. ORing in a k-bit number fills exactly those zeros, so the bits of x end up right after the old string.
Why does i & (i - 1) == 0 detect a power of two?
A power of two has a single 1 bit. Subtracting 1 turns that bit off and sets every lower bit, so the AND is zero. Any other positive number keeps its highest 1 bit in the AND.
Is it safe to take the modulo after every step?
Yes. (v * 2^k + x) mod m depends only on v mod m, so reducing early gives the same final answer while keeping every number small.