Find the K-or of an Array — Easy Problem & Solution
The K-or of an array is the number whose bit i is set exactly when at least k elements of nums have bit i set. Return the K-or of nums.
- Difficulty: Easy
- Topics: Arrays, Bit Manipulation
- Asked at: Amazon, TCS, Infosys
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
The K-or of an array is the number whose bit i is set exactly when at least k elements of nums have bit i set.
Return the K-or of nums.
Example 1
Input: nums = [7,12,9,8,9,15], k = 4
Output: 9
Explanation: Bit 0 is set in 7, 9, 9 and 15 — four elements — and bit 3 is set in 12, 9, 8, 9 and 15. No other bit reaches four.
Example 2
Input: nums = [2,12,1,11,4,5], k = 6
Output: 0
Explanation: No bit is set in all six numbers.
Example 3
Input: nums = [10,8,5,9,11,6,8], k = 1
Output: 15
Explanation: With k = 1 the K-or is the plain OR of everything.
Constraints
1 <= nums.length <= 500 <= nums[i] < 2^311 <= k <= nums.length
How to solve Find the K-or of an Array
The definition is per-bit, so handle one bit at a time: count the elements that have it, and set it in the answer when the count reaches k.
Approach
- Loop
bfrom0to30. - Count the elements whose bit
bis set. - If that count is at least
k, add2^bto the answer.
Why it works
Bits of the answer are defined independently of one another, so no interaction or carry logic is needed — the loop is a direct transcription of the definition.
Complexity
- Time —
O(31 · n) - Space —
O(1)
Pitfalls
- Values reach
2^31 - 1, so bit 30 matters and bit 31 does not exist for a signedint. - In JavaScript
1 << 31is negative — build the answer by adding powers of two instead of shifting into the sign bit. k = 1reduces to the ordinary OR, which is a useful sanity check.
Reference solution
Python
from typing import List
def findKOr(nums: List[int], k: int) -> int:
out = 0
for b in range(31):
if sum(1 for x in nums if (x >> b) & 1) >= k:
out |= 1 << b
return outJavaScript
var findKOr = function(nums, k) {
var out = 0;
for (var b = 0; b < 31; b++) {
var c = 0;
for (var i = 0; i < nums.length; i++) {
if (Math.floor(nums[i] / Math.pow(2, b)) % 2 === 1) c++;
}
if (c >= k) out += Math.pow(2, b);
}
return out;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.