Concatenation of Consecutive Binary Numbers - Problem

You're given an integer n, and your task is to create a binary concatenation sequence. Here's how it works:

  1. Convert each number from 1 to n into its binary representation
  2. Concatenate all these binary strings together in order
  3. Convert the final concatenated binary string back to decimal
  4. Return the result modulo 109 + 7

Example: For n = 3:

  • 1 in binary: "1"
  • 2 in binary: "10"
  • 3 in binary: "11"
  • Concatenated: "11011"
  • Decimal value: 27

The challenge lies in handling large values of n efficiently, as the concatenated binary string can become extremely long. You'll need to use bit manipulation techniques to avoid actually building the string!

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 1
โ€บ Output: 1
๐Ÿ’ก Note: Only number 1, binary is '1', decimal value is 1
example_2.py โ€” Small Sequence
$ Input: n = 3
โ€บ Output: 27
๐Ÿ’ก Note: 1โ†’'1', 2โ†’'10', 3โ†’'11'. Concatenated: '11011' = 16+8+2+1 = 27
example_3.py โ€” Larger Case
$ Input: n = 12
โ€บ Output: 505379714
๐Ÿ’ก Note: Binary sequence: '1101110010110111000100110101111110011011' converted to decimal and taken modulo 10^9+7

Visualization

Tap to expand
Binary Concatenation Chain Builder1"1"2"10"3"11"..."..."Mathematical Chain Building ProcessStep 1: result = 0, add "1" โ†’ result = 1Step 2: result = 1, shift left 2, add 2 โ†’ result = (1 << 2) + 2 = 6Step 3: result = 6, shift left 2, add 3 โ†’ result = (6 << 2) + 3 = 27Key InsightInstead of building string "11011",use bit operations for O(1) space!ComplexityTime: O(n) - single passSpace: O(1) - no string storageFinal Result: "11011" = 27 (mod 10^9 + 7)
Understanding the Visualization
1
Initialize Chain
Start with empty result = 0
2
Add Number 1
1 has 1 bit, result becomes 1
3
Add Number 2
2 has 2 bits, shift result left 2 positions, add 2: result = 6
4
Add Number 3
3 has 2 bits, shift result left 2 positions, add 3: result = 27
5
Continue Pattern
Keep shifting and adding for all numbers up to n
Key Takeaway
๐ŸŽฏ Key Insight: Use bit shifting `(result << bits) + number` instead of string concatenation to achieve O(n) time and O(1) space complexity while handling modular arithmetic efficiently.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single loop through numbers 1 to n, with O(1) operations per iteration

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only uses a constant amount of extra space for variables

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค n โ‰ค 105
  • Result must be returned modulo 109 + 7
  • The concatenated binary string can be extremely long
Asked in
Facebook 45 Google 35 Amazon 28 Microsoft 22
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen