Sum of Compatible Numbers in Range I solution and explanation
4 more videos on this problem
3954. Sum of Compatible Numbers in Range I (Leetcode Easy)Programming Live with Larry · 2:47 · 203 views
Sum of Compatible Numbers in Range I | LeetCode 3954 | Weekly Contest 505 | Java | Developer CoderDeveloper Coder · 5:49 · 163 views
leetcode 3954 | weekly contest 505 | Sum of Compatible Numbers in Range I | MathCode With Vick · 5:18 · 145 views
LeetCode Weekly Contest | Q1 - Sum of Compatible Numbers in Range IGopo workspace · 3:12 · 59 views
Sum of Compatible Numbers in Range I | Leetcode weekly contest 505 | #3954UMANG AGRAWAL · 3:09 · 36 views
The problem
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.
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, sinceabs(2 - 1) = 1and2 & 1 = 0.x = 4, sinceabs(2 - 4) = 2and2 & 4 = 0.x = 5, sinceabs(2 - 5) = 3and2 & 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 <= 1001 <= k <= 100
Approach overview
Problem Overview: You are given numbers and a range constraint. A number is considered compatible with another if their bit representations do not conflict (commonly checked using (a & b) == 0). The task is to compute the sum of numbers within a given range that satisfy this compatibility rule.
Approach 1: Brute Force Scan (O(n) time, O(1) space)
The most direct solution iterates through every number in the specified range and checks compatibility using a bitwise AND operation. If (num & target) == 0, the number is compatible and contributes to the running sum. This approach relies only on a simple loop and a constant‑time bit operation. It works well when the range size is small, but performance degrades when the range grows large because every candidate must be evaluated individually.
Approach 2: Precompute Compatible Masks with Frequency Map (O(n) preprocessing, near O(1) query)
When the input contains many numbers or repeated queries, you can precompute counts or sums of numbers by their bitmask representation. Store the frequency or sum of each mask in a hash map or array indexed by mask. For a given target mask, any compatible number must satisfy (mask & target) == 0. Iterating through stored masks and summing those that satisfy the condition avoids rescanning the entire range repeatedly. Hash lookups make this significantly faster in practice.
Approach 3: Bitmask Subset Enumeration (O(2^b) time, O(2^b) space)
If the number of bits b is small (for example ≤20), build a table storing the sum of numbers for each bitmask. Instead of checking every value directly, enumerate all masks that are subsets of the complement of the target mask. Each valid subset automatically satisfies the compatibility condition. This technique appears often in bitmask and bit manipulation problems where compatibility constraints depend on shared bits.
Recommended for interviews: Start with the brute force scan because it clearly demonstrates the compatibility condition and the use of (a & b). Then move to the bitmask or frequency‑based optimization. Interviewers typically expect you to recognize that compatibility is a bitwise property and that precomputing masks or using subset enumeration can reduce repeated work.
Solution
We iterate through x within the range [max(1, n - k), n + k]. If the bitwise AND result of n and x is 0, we accumulate x into the answer.
After the iteration ends, simply return the answer.
The time complexity is O(k), and the space complexity is O(1).
class Solution:
def sumOfGoodIntegers(self, n: int, k: int) -> int:
ans = 0
for x in range(max(1, n - k), n + k + 1):
if (n & x) == 0:
ans += x
return ansclass Solution {
public int sumOfGoodIntegers(int n, int k) {
int ans = 0;
int start = Math.max(1, n - k);
int end = n + k;
for (int x = start; x <= end; x++) {
if ((n & x) == 0) {
ans += x;
}
}
return ans;
}
}class Solution {
public:
int sumOfGoodIntegers(int n, int k) {
int ans = 0;
int start = max(1, n - k);
int end = n + k;
for (int x = start; x <= end; ++x) {
if ((n & x) == 0) {
ans += x;
}
}
return ans;
}
};function sumOfGoodIntegers(n: number, k: number): number {
let ans = 0;
const start = Math.max(1, n - k);
const end = n + k;
for (let x = start; x <= end; x++) {
if ((n & x) === 0) {
ans += x;
}
}
return ans;
}func sumOfGoodIntegers(n int, k int) (ans int) {
start := max(1, n-k)
end := n + k
for x := start; x <= end; x++ {
if (n & x) == 0 {
ans += x
}
}
return
}Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Range Scan | O(n) | O(1) | Small ranges or single query where simplicity matters |
| Hash Map / Frequency by Bitmask | O(n) preprocessing + O(m) mask checks | O(n) | Multiple queries or repeated compatibility checks |
| Bitmask Subset Enumeration | O(2^b) | O(2^b) | When bit width is small and compatibility depends on bit patterns |
Frequently asked questions
Is Sum of Compatible Numbers in Range I easy or hard?
The problem is typically classified as Easy because the main logic relies on a single compatibility check using bitwise AND. The challenge comes from recognizing that compatibility is determined by shared bits and then implementing the range scan efficiently.
Sum of Compatible Numbers in Range I Python/Java solution
In Python or Java, the core logic is a loop that checks the compatibility condition using the bitwise AND operator. If (num & target) == 0, add the number to the running sum. Both languages support efficient bit operations, so the implementation remains straightforward and runs in O(n) time.
How to solve Sum of Compatible Numbers in Range I in O(n)?
Iterate through the range once and check compatibility using the bitwise condition (num & target) == 0. Maintain a running sum for all numbers that satisfy the condition. Since each check is constant time, the full pass over n numbers results in O(n) time and O(1) extra space.
What is the best approach for Sum of Compatible Numbers in Range I?
The best approach depends on input size. A brute force scan works in O(n) time and is often acceptable for small ranges. For larger inputs or repeated queries, precomputing sums by bitmask or using subset enumeration reduces repeated compatibility checks and significantly improves performance.
Is Sum of Compatible Numbers in Range I asked at Google/Amazon/Meta?
Bit manipulation and compatibility checks using bitwise AND frequently appear in interviews at companies like Google, Amazon, and Meta. Variants involving subset masks or compatible bit patterns are common because they test understanding of low‑level operations and optimization strategies.
What data structure is used in Sum of Compatible Numbers in Range I?
The basic solution only needs simple variables for iteration and summation. Optimized solutions often use hash maps or arrays indexed by bitmask to store counts or sums of numbers, enabling faster compatibility lookups.
What is the time complexity of Sum of Compatible Numbers in Range I?
The straightforward solution runs in O(n) time because each number in the range is checked with a constant‑time bitwise AND operation. Optimized approaches using bitmask preprocessing or subset enumeration can reduce repeated work, often achieving near O(1) query time after preprocessing.
