#2917

Find the K-or of an Array

Easy
ArrayBit ManipulationBit ManipulationArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a single pass through the array to count the bits directly, resulting in a more efficient algorithm. We keep track of how many numbers have each bit set and build the result in a single loop.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an array to count the number of set bits for each of the 32 bit positions.
  2. 2Step 2: Loop through each number in the array and update the count for each bit position.
  3. 3Step 3: Initialize the result to 0.
  4. 4Step 4: Loop through the count array and if any bit count is greater than or equal to k, set that bit in the result.
  5. 5Step 5: Return the result.
solution.py13 lines
1# Full working Python code
2
3def k_or(nums, k):
4    count = [0] * 32
5    for num in nums:
6        for bit in range(32):
7            if (num >> bit) & 1:
8                count[bit] += 1
9    result = 0
10    for bit in range(32):
11        if count[bit] >= k:
12            result |= (1 << bit)
13    return result

Complexity note: The time complexity is O(n) because we only go through the array once to count the bits and then once more to build the result. The space complexity is O(1) since we use a fixed-size array of size 32.

  • 1Understanding bit manipulation is crucial for solving problems involving binary operations.
  • 2Counting occurrences of bits across multiple numbers can lead to efficient solutions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.