Find N distinct numbers whose bitwise Or is equal to K in Python

Given two integers N and K, we need to find N distinct numbers whose bitwise OR equals K. If no such combination exists, we return -1.

For example, if N = 4 and K = 6, one possible output is [6, 0, 1, 2] because 6 | 0 | 1 | 2 = 6.

Algorithm Approach

The key insight is that we need at least 2^(number of set bits in K) different numbers to construct all possible combinations. We start with K itself, then generate additional numbers by systematically setting different bit patterns.

Implementation

def find_n_numbers_with_or_k(n, k):
    MAX = 32
    visited = [False] * MAX
    result = []
    
    def count_set_bits(num):
        """Count number of set bits in a number"""
        if num == 0:
            return 0
        return (num & 1) + count_set_bits(num >> 1)
    
    def add_number(num):
        """Generate a number using available bit positions"""
        value = 0
        for i in range(MAX):
            if visited[i]:
                continue
            if num & 1:
                value += (1 << i)
            num = num // 2
        result.append(value)
    
    # Calculate powers of 2 for efficiency
    pow2 = [2**i for i in range(MAX)]
    
    # Start with K itself
    result.append(k)
    
    # Count set bits in K
    cnt_k = count_set_bits(k)
    
    # Check if solution is possible
    if pow2[cnt_k] < n:
        return -1
    
    # Generate remaining N-1 numbers
    count = 1  # Already added K
    for i in range(pow2[cnt_k] - 1):
        if count == n:
            break
        add_number(i)
        count += 1
    
    return result

# Test the function
n = 4
k = 6
numbers = find_n_numbers_with_or_k(n, k)
print(f"N distinct numbers: {numbers}")

# Verify the OR result
if numbers != -1:
    or_result = 0
    for num in numbers:
        or_result |= num
    print(f"Bitwise OR: {or_result}")
    print(f"Expected K: {k}")
    print(f"Valid solution: {or_result == k}")
N distinct numbers: [6, 0, 1, 2]
Bitwise OR: 6
Expected K: 6
Valid solution: True

How It Works

The algorithm works by understanding that to generate N distinct numbers with OR equal to K, we need:

  • At least 2^(set bits in K) possible combinations
  • Start with K itself to ensure the OR includes all required bits
  • Generate additional numbers using different bit patterns
  • Each additional number contributes to the final OR without changing the result

Example Walkthrough

For N=4 and K=6 (binary: 110):

# K = 6 (binary: 110) has 2 set bits
# We need 2^2 = 4 possible combinations minimum
# Solution: [6, 0, 1, 2]

numbers = [6, 0, 1, 2]
print("Binary representation:")
for num in numbers:
    print(f"{num}: {bin(num)}")

print(f"\nOR result: {6 | 0 | 1 | 2} = {bin(6 | 0 | 1 | 2)}")
Binary representation:
6: 0b110
0: 0b0
1: 0b1
2: 0b10

OR result: 6 = 0b110

Edge Cases

# Test impossible case
result1 = find_n_numbers_with_or_k(10, 1)  # K=1 has only 1 set bit, 2^1=2 < 10
print(f"N=10, K=1: {result1}")

# Test simple case
result2 = find_n_numbers_with_or_k(2, 7)   # K=7 has 3 set bits, 2^3=8 >= 2
print(f"N=2, K=7: {result2}")
N=10, K=1: -1
N=2, K=7: [7, 0]

Conclusion

This algorithm efficiently finds N distinct numbers with bitwise OR equal to K by leveraging the relationship between set bits and possible combinations. The time complexity is O(N) and it handles edge cases where no solution exists.

Updated on: 2026-03-25T09:48:08+05:30

222 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements