Find the K-or of an Array - Problem

You are given an integer array nums and an integer k. Your task is to compute the K-or of the array, which is a variation of the standard bitwise OR operation.

In the K-or operation, a bit position in the result is set to 1 if and only if at least k numbers in the array have a 1 in that same bit position. Otherwise, the bit is set to 0.

Example: If nums = [7, 12, 9, 8, 9, 15] and k = 4, we need to find which bit positions have at least 4 numbers with a 1 bit. The binary representations are:

  • 7 → 0111
  • 12 → 1100
  • 9 → 1001
  • 8 → 1000
  • 9 → 1001
  • 15 → 1111

Count the 1s in each position and keep only positions where the count ≥ k.

Input & Output

example_1.py — Basic K-or Operation
$ Input: nums = [7, 12, 9, 8, 9, 15], k = 4
Output: 9
💡 Note: Binary representations: 7→0111, 12→1100, 9→1001, 8→1000, 9→1001, 15→1111. Bit 0 appears in 4 numbers (7,9,9,15), bit 3 appears in 4 numbers (12,9,8,15). Result: 1001₂ = 9
example_2.py — High Threshold
$ Input: nums = [2, 12, 1, 3, 4], k = 6
Output: 0
💡 Note: No bit position appears in 6 or more numbers since we only have 5 numbers total. Result is 0.
example_3.py — All Bits Set
$ Input: nums = [15, 15, 15], k = 2
Output: 15
💡 Note: 15 in binary is 1111. All bit positions (0,1,2,3) appear in at least 2 numbers. Result: 1111₂ = 15

Constraints

  • 1 ≤ nums.length ≤ 50
  • 0 ≤ nums[i] < 231
  • 1 ≤ k ≤ nums.length

Visualization

Tap to expand
K-or as Democratic VotingVoters (Numbers):7votes: 0,1,212votes: 2,39votes: 0,315votes: 0,1,2,3Vote Counting (k=3):03 votes ≥ 3 ✓ PASS12 votes < 3 ✗ FAIL23 votes ≥ 3 ✓ PASS33 votes ≥ 3 ✓ PASSResult:Winning Proposals1101₂= 13💡 Key InsightK-or is like a democratic election where each bit position is a proposaland each number votes on proposals corresponding to its set bits.Only proposals with ≥ k votes become part of the final result.This makes the bit manipulation concept much more intuitive!
Understanding the Visualization
1
Cast Votes
Each number votes 'yes' on proposals corresponding to its set bits
2
Count Votes
Tally votes for each of the 32 proposals
3
Determine Winners
Proposals with ≥ k votes pass and get set in the result
Key Takeaway
🎯 Key Insight: K-or extends regular OR by requiring a minimum vote threshold, making it perfect for finding commonly set bits across multiple numbers.
Asked in
Meta 15 Amazon 12 Microsoft 8 Google 5
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen