Sum of Compatible Numbers in Range II Problem
Description
LeetCode Problem 4115.
You are given two integers n and k.
A positive integer x is called compatible if it satisfies both of the following conditions:
abs(n - x) <= k(n & x) == 0
Return the sum of all compatible integers x.
Since the answer may be very large, return it modulo 10^9 + 7.
Note:
- Here,
&denotes the bitwise AND operator. - The absolute difference between integers
iandjis defined asabs(i - j).
Example 1:
Input: n = 2, k = 3
Output: 10
Explanation:
The compatible integers are:
- x = 1, since abs(2 - 1) = 1 and 2 & 1 = 0.
- x = 4, since abs(2 - 4) = 2 and 2 & 4 = 0.
- x = 5, since abs(2 - 5) = 3 and 2 & 5 = 0.
Thus, the answer is 1 + 4 + 5 = 10.
Example 2:
Input: n = 5, k = 1
Output: 0
Explanation:
There are no compatible integers in the range [4, 6]. Thus, the answer is 0.
Constraints:
1 <= n <= 10^150 <= k <= 10^15
Solution
Approach: Digit DP
Let lo = max(1, n - k) and hi = n + k. The answer is calc(hi) - calc(lo - 1) modulo 109+7, where calc(x) is the sum of all integers in [0, x] that share no set bit with n. The value 0 adds nothing to a sum, so it does no harm.
To compute calc(x), choose the bits of the number from the highest bit down, with memoization. The state is (i, lim): we are about to choose bit i, and lim says whether the bits chosen so far are still equal to the top bits of x (if so, bit i cannot exceed bit i of x). Each call returns two values for the bits i down to 0: how many ways there are to finish the number, and the sum of the lower parts of those numbers.
Try cur = 0 and cur = 1. Skip cur = 1 when bit i of n is set, because that would make x & n non-zero. After recursing on bit i - 1, which returns cnt1 ways and a lower sum s1, add cnt1 to the count and s1 + cnt1 * cur * 2^i to the sum, reducing modulo 109+7 as you go.
Both calls use the bit length of hi; the smaller bound simply has leading zeros. The memo depends on x, so clear it before each call.
Complexity: O(log(n + k)) time and O(log(n + k)) space.
from functools import lru_cache
class Solution:
def sumOfGoodIntegers(self, n: int, k: int) -> int:
@lru_cache(None)
def dfs(i: int, lim: bool) -> Tuple[int, int]:
if i < 0:
return 1, 0
up = (num >> i & 1) if lim else 1
cnt = s = 0
for cur in range(up + 1):
if (n >> i & 1) == 1 and cur == 1:
continue
cnt1, s1 = dfs(i - 1, lim and cur == up)
cnt += cnt1
s += s1 + cnt1 * (cur << i) % mod
return cnt, s % mod
mod = 10**9 + 7
lo, hi = max(1, n - k), n + k
m = hi.bit_length()
num = hi
right = dfs(m - 1, True)[1]
dfs.cache_clear()
num = lo - 1
left = dfs(m - 1, True)[1]
dfs.cache_clear()
return (right - left + mod) % mod