Skip to content

2917. Find the K-or of an Array 👎

  • Time: $O(30n) = O(n)$
  • Space: $O(n)$
1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int findKOr(int[] nums, int k) {
    final int kMaxBit = 30;
    int ans = 0;

    for (int i = 0; i <= kMaxBit; ++i) {
      final int finalI = i;
      final int count = (int) Arrays.stream(nums)
                            .filter(num -> (num >> finalI & 1) == 1) //
                            .count();
      if (count >= k)
        ans += Math.pow(2, i);
    }

    return ans;
  }
}
1
2
3
4
5
6
class Solution:
  def findKOr(self, nums: list[int], k: int) -> int:
    kMaxBit = 30
    return sum(2**i
               for i in range(kMaxBit + 1)
               if sum(num >> i & 1 for num in nums) >= k)