Concatenation of Consecutive Binary Numbers (LeetCode 1680): Solution and Explanation

Medium
Math
Bit Manipulation
Simulation

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

  1. Set result = 0 and length = 0.
  2. For each i from 1 to n: if i & (i - 1) == 0, i is a power of two, so increase length by one.
  3. Set result = ((result << length) | i) % MOD.
  4. Return result.

Step-by-step example

n = 3
  1. Start with result = 0 and length = 0.
  2. i = 1 is a power of two, so length = 1. result = (0 << 1) | 1 = 1, the string "1".
  3. i = 2 is a power of two, so length = 2. result = (1 << 2) | 2 = 100 | 10 = 110 = 6, the string "110".
  4. i = 3 is not a power of two, so length stays 2. result = (6 << 2) | 3 = 11000 | 11 = 11011 = 27.
  5. 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 result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Running value with shift and OR O(n)
Bit length per number O(n)
Build the string, then parse O(n log n)
Time

O(n)

Each number from 1 to n is appended once with a constant amount of work.

Space

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.