Find the K-or of an Array - Problem

You are given an integer array nums and an integer k.

Let's introduce K-or operation by extending the standard bitwise OR. In K-or, a bit position in the result is set to 1 if at least k numbers in nums have a 1 in that position.

Return the K-or of nums.

Input & Output

Example 1 — Basic Case
$ Input: nums = [7,12,9,8,9,15], k = 4
Output: 9
💡 Note: Binary: 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 (8,9,9,12). Result = 1001₂ = 9
Example 2 — Higher Threshold
$ Input: nums = [2,12,1,3,4,5], k = 3
Output: 0
💡 Note: No bit position appears in 3 or more numbers, so K-or result is 0
Example 3 — Low Threshold
$ Input: nums = [10,8,5,9,11,6,8], k = 2
Output: 15
💡 Note: Multiple bit positions have count ≥ 2. Result combines all qualifying bits to get 15

Constraints

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

Visualization

Tap to expand
K-or of an Array INPUT nums array: 7 12 9 8 9 15 Binary (bits 3-0): 7 = 0111 12 = 1100 9 = 1001 8 = 1000 9 = 1001 15 = 1111 k = 4 Need 4+ ones per bit ALGORITHM STEPS 1 Initialize result = 0 Track bits meeting threshold 2 For each bit position Iterate bits 0 to 31 3 Count ones at bit i Sum (nums[j] >> i) & 1 Bit Position Counts: Bit 3: 4 ones >=4 OK Bit 2: 2 ones <4 NO Bit 1: 3 ones <4 NO Bit 0: 5 ones >=4 OK 4 Set bit if count >= k result |= (1 << i) FINAL RESULT K-or computation: Bit Analysis Bit 3: count=4 >= 4 SET Bit 2: count=2 < 4 OFF Bit 1: count=3 < 4 OFF Bit 0: count=5 >= 4 SET Result = 1001 binary Output: 9 Binary: 1001 Bits 3 and 0 are set (each has 4+ ones) Key Insight: K-or extends bitwise OR by requiring at least k numbers to have a 1 at each bit position. Single pass: iterate each bit (0-31), count how many numbers have that bit set, and set the result bit if count >= k. Time: O(32*n) = O(n), Space: O(1). TutorialsPoint - Find the K-or of an Array | Single Pass Bit Accumulation
Asked in
Amazon 15 Microsoft 12
8.9K Views
Medium Frequency
~15 min Avg. Time
245 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