#1680

Concatenation of Consecutive Binary Numbers

Medium
MathBit ManipulationSimulationBit ManipulationSimulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach leverages bit manipulation to build the result incrementally without creating a large binary string. By keeping track of the current result and the number of bits each integer contributes, we can efficiently compute the final value.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize result to 0 and a variable to track the total number of bits used.
  2. 2Step 2: Loop through each integer from 1 to n.
  3. 3Step 3: For each integer, calculate its bit length and shift the result left by that many bits, then add the integer.
  4. 4Step 4: After processing all integers, return the result modulo (10^9 + 7).
solution.py7 lines
1def concatenatedBinary(n):
2    result = 0
3    for i in range(1, n + 1):
4        result = (result << i.bit_length()) | i
5    return result % (10**9 + 7)
6
7print(concatenatedBinary(3))

Complexity note: The time complexity is O(n) because we iterate through each integer from 1 to n exactly once, and the operations performed inside the loop (bit shifting and bitwise OR) are constant time operations. The space complexity is O(1) since we only use a fixed amount of space for variables.

  • 1Understanding bit manipulation can significantly optimize performance for problems involving binary representations.
  • 2Using modulo operations early can help prevent overflow in languages with fixed integer sizes.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.