#3370

Smallest Number With All Set Bits

Easy
MathBit ManipulationBit ManipulationMathematical Properties
LeetCode ↗

Approaches

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

Intuition

Time O(log n)Space O(1)

The optimal approach leverages the fact that the smallest number with all set bits is always of the form (2^k - 1). We find the next power of 2 greater than or equal to n and subtract 1.

⚙️

Algorithm

2 steps
  1. 1Step 1: Find the smallest power of 2 that is greater than or equal to n.
  2. 2Step 2: Subtract 1 from that power of 2 to get the result.
solution.py7 lines
1# Full working Python code
2
3def smallest_number_with_all_set_bits(n):
4    power = 1
5    while power < n:
6        power <<= 1
7    return power - 1

Complexity note: The time complexity is O(log n) because we are doubling the power of 2 until we reach or exceed n, which is logarithmic in nature.

  • 1The smallest number with all set bits is always of the form (2^k - 1).
  • 2Finding the next power of 2 can be done efficiently using bit manipulation.

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