Find Nth Smallest Integer With K One Bits Problem
Description
LeetCode Problem 3821.
You are given two positive integers n and k.
Return an integer denoting the n^th smallest positive integer that has exactly k ones in its binary representation. It is guaranteed that the answer is strictly less than 2^50.
Example 1:
Input: n = 4, k = 2
Output: 9
Explanation:
The 4 smallest positive integers that have exactly k = 2 ones in their binary representations are:
- 3 = 11_2
- 5 = 101_2
- 6 = 110_2
- 9 = 1001_2
Example 2:
Input: n = 3, k = 1
Output: 4
Explanation:
The 3 smallest positive integers that have exactly k = 1 one in their binary representations are:
- 1 = 1_2
- 2 = 10_2
- 4 = 100_2
Constraints:
1 <= n <= 2^501 <= k <= 50- The answer is strictly less than
2^50.
Solution
Approach: Combinatorics + Greedy
Decide the bits of the answer from the highest (bit 49) down to bit 0. Suppose we are at bit i and still have to place k ones.
If bit i is 0, all k ones go into the i lower bits, which gives C(i, k) numbers, and they are all smaller than any number whose bit i is 1. So if n <= C(i, k) the answer has a 0 here. Otherwise the answer has a 1 here: subtract C(i, k) from n (we skip those smaller numbers) and decrease k by one.
Stop when k reaches 0; the remaining lower bits are zero. Pascal's triangle gives all the binomials up front.
Complexity: O(log^2 M) time and space for the table, where M = 2^50; the greedy pass itself is O(log M).
mx = 50
c = [[0] * (mx + 1) for _ in range(mx)]
for i in range(mx):
c[i][0] = 1
for j in range(1, i + 1):
c[i][j] = c[i - 1][j - 1] + c[i - 1][j]
class Solution:
def nthSmallest(self, n: int, k: int) -> int:
ans = 0
for i in range(49, -1, -1):
if n > c[i][k]:
n -= c[i][k]
ans |= 1 << i
k -= 1
if k == 0:
break
return ans