#3309

Maximum Possible Number by Binary Concatenation

Medium
ArrayBit ManipulationEnumerationSortingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n!)
O(n log n)
Space
O(n)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

Instead of generating all permutations, we can leverage the fact that the maximum binary number is formed by prioritizing larger binary representations. We can sort the numbers based on their binary length and value.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the array based on the binary representation length and value.
  2. 2Step 2: Concatenate the binary representations of the sorted numbers.
  3. 3Step 3: Convert the concatenated binary string to a decimal number.
solution.py4 lines
1def maxBinaryConcatenation(nums):
2    nums.sort(key=lambda x: (len(bin(x)[2:]), x), reverse=True)
3    binary_string = ''.join(bin(num)[2:] for num in nums)
4    return int(binary_string, 2)

Complexity note: The time complexity is O(n log n) due to sorting the array based on binary representation characteristics. The space complexity is O(n) for storing the binary string.

  • 1Sorting based on binary length and value maximizes the concatenated number.
  • 2Binary representations can be compared directly based on their lengths.

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