#3821
Find Nth Smallest Integer With K One Bits
HardMathBit ManipulationCombinatoricsCombinatoricsBit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Use combinatorial mathematics to directly calculate the nth integer with k ones by determining how many valid integers exist for each bit length.
⚙️
Algorithm
3 steps- 1Step 1: Precompute binomial coefficients C(i, k) for i from k to 50.
- 2Step 2: Iterate through bit lengths, using the coefficients to count how many integers with k ones fit within the current range.
- 3Step 3: Construct the nth integer by placing ones in the appropriate bit positions based on the counts.
solution.py15 lines
1from math import comb
2
3def nthSmallest(n, k):
4 result, bits = 0, 0
5 while True:
6 if comb(bits, k) >= n:
7 break
8 n -= comb(bits, k)
9 bits += 1
10 for i in range(bits, -1, -1):
11 if comb(i, k) >= n:
12 result |= 1 << i
13 n -= comb(i, k)
14 k -= 1
15 return resultℹ
Complexity note: The algorithm efficiently computes the result using combinatorial counting, leading to linear complexity in terms of n.
- 1Understanding binary representation is crucial.
- 2Combinatorial counting helps in efficiently finding the nth integer.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.