Facebook Pixel

2980. Check if Bitwise OR Has Trailing Zeros

EasyBit ManipulationArray
Leetcode Link

Problem Description

You are given an array of positive integers nums.

Your task is to determine if you can select two or more elements from the array such that when you perform a bitwise OR operation on all selected elements, the result has at least one trailing zero in its binary representation.

A trailing zero means the binary number ends with a 0. For example:

  • The number 5 has binary representation "101" - this has no trailing zeros
  • The number 4 has binary representation "100" - this has two trailing zeros

The key insight is that for a bitwise OR result to have a trailing zero, all selected numbers must have their least significant bit (rightmost bit) as 0. This only happens when all selected numbers are even, since:

  • Even numbers have binary representations ending in 0 (like 2 = "10", 4 = "100", 6 = "110")
  • Odd numbers have binary representations ending in 1 (like 1 = "1", 3 = "11", 5 = "101")

When you OR even numbers together, the result remains even (ends with 0). But if you include even one odd number in the OR operation, the result becomes odd (ends with 1).

The solution counts how many even numbers exist in the array using x & 1 ^ 1, which evaluates to 1 for even numbers and 0 for odd numbers. If there are at least 2 even numbers, we can select them to get a bitwise OR with trailing zeros, so the function returns true. Otherwise, it returns false.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

Let's think about when a bitwise OR operation produces a trailing zero. A trailing zero means the last bit (least significant bit) of the result is 0.

In bitwise OR, a bit position in the result is 0 only when all corresponding bits in the operands are 0. If even one operand has a 1 in that position, the result will have a 1 there.

For the last bit position:

  • Even numbers have 0 as their last bit (e.g., 2 = 10, 4 = 100, 6 = 110)
  • Odd numbers have 1 as their last bit (e.g., 1 = 1, 3 = 11, 5 = 101)

So for the OR result to have a trailing zero, we need all selected numbers to be even. If we include even one odd number, its last bit of 1 will make the entire OR result have 1 as the last bit, eliminating any trailing zeros.

Now the problem reduces to: "Can we select two or more even numbers from the array?"

This is simply checking if we have at least 2 even numbers in the array. If we do, we can select them, and their bitwise OR will definitely have at least one trailing zero.

The expression x & 1 ^ 1 cleverly checks if a number is even:

  • x & 1 gives us the last bit (0 for even, 1 for odd)
  • ^ 1 flips the bit (0 becomes 1, 1 becomes 0)
  • So the expression returns 1 for even numbers and 0 for odd numbers

By summing this expression over all array elements, we count the even numbers. If this count is >= 2, we return true.

Solution Approach

The solution uses a simple counting approach to determine if we can select elements whose bitwise OR has trailing zeros.

Implementation Steps:

  1. Count Even Numbers: We iterate through the array and count how many even numbers are present.

  2. Bit Manipulation for Even Check: For each number x in the array:

    • x & 1 performs a bitwise AND with 1, which extracts the least significant bit
      • If x is even: x & 1 = 0 (since even numbers end with 0)
      • If x is odd: x & 1 = 1 (since odd numbers end with 1)
    • x & 1 ^ 1 applies XOR with 1 to flip the bit
      • If x is even: 0 ^ 1 = 1
      • If x is odd: 1 ^ 1 = 0
    • This gives us 1 for even numbers and 0 for odd numbers
  3. Sum and Compare: The expression sum(x & 1 ^ 1 for x in nums) counts the total number of even numbers in the array.

  4. Return Result: If the count is >= 2, we return true because we can select at least two even numbers whose bitwise OR will have trailing zeros. Otherwise, return false.

Time Complexity: O(n) where n is the length of the array, as we iterate through each element once.

Space Complexity: O(1) as we only use a constant amount of extra space for the counting operation.

The elegance of this solution lies in recognizing that the problem is essentially asking whether we have at least two even numbers in the array, which can be determined with a single pass and simple bit manipulation.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution with a concrete example to understand how it works.

Example: nums = [3, 2, 8, 5, 4]

Step 1: Identify which numbers are even

Let's check each number using the bit manipulation technique x & 1 ^ 1:

  • 3 (binary: 011):

    • 3 & 1 = 1 (last bit is 1)
    • 1 ^ 1 = 0 → 3 is odd
  • 2 (binary: 010):

    • 2 & 1 = 0 (last bit is 0)
    • 0 ^ 1 = 1 → 2 is even ✓
  • 8 (binary: 1000):

    • 8 & 1 = 0 (last bit is 0)
    • 0 ^ 1 = 1 → 8 is even ✓
  • 5 (binary: 101):

    • 5 & 1 = 1 (last bit is 1)
    • 1 ^ 1 = 0 → 5 is odd
  • 4 (binary: 100):

    • 4 & 1 = 0 (last bit is 0)
    • 0 ^ 1 = 1 → 4 is even ✓

Step 2: Count the even numbers

Sum of (x & 1 ^ 1) for all numbers: 0 + 1 + 1 + 0 + 1 = 3

We have 3 even numbers: [2, 8, 4]

Step 3: Check if we can form a valid selection

Since we have 3 even numbers (≥ 2), we can select two or more of them.

Step 4: Verify the result

Let's verify by selecting two even numbers, say 2 and 8:

  • 2 in binary: 010
  • 8 in binary: 1000
  • 2 OR 8 = 1010 (decimal 10)

The result 1010 ends with a 0, confirming it has a trailing zero!

We could also select all three even numbers 2 OR 8 OR 4:

  • Result: 1110 (decimal 14)
  • This also ends with 0, having a trailing zero.

Answer: Return true because we have at least 2 even numbers that we can select to produce a bitwise OR with trailing zeros.

Solution Implementation

1class Solution:
2    def hasTrailingZeros(self, nums: List[int]) -> bool:
3        # Count how many even numbers are in the array
4        # For a number to have trailing zeros when represented in binary,
5        # we need at least two even numbers whose bitwise OR has trailing zeros
6      
7        # Count even numbers in the array
8        # x & 1 returns 0 for even numbers and 1 for odd numbers
9        # (x & 1) ^ 1 inverts this: returns 1 for even numbers and 0 for odd numbers
10        even_count = sum((x & 1) ^ 1 for x in nums)
11      
12        # Return True if there are at least 2 even numbers
13        return even_count >= 2
14
1class Solution {
2    public boolean hasTrailingZeros(int[] nums) {
3        // Count the number of even integers in the array
4        int evenCount = 0;
5      
6        // Iterate through each number in the array
7        for (int number : nums) {
8            // Check if the number is even by examining its least significant bit
9            // (number & 1) returns 0 for even numbers, 1 for odd numbers
10            // XOR with 1 flips the result: 0 -> 1 (even), 1 -> 0 (odd)
11            evenCount += ((number & 1) ^ 1);
12        }
13      
14        // Return true if there are at least 2 even numbers
15        // (even numbers have trailing zeros in binary representation)
16        return evenCount >= 2;
17    }
18}
19
1class Solution {
2public:
3    bool hasTrailingZeros(vector<int>& nums) {
4        // Count how many even numbers are in the array
5        // (even numbers have trailing zeros in binary representation)
6        int evenCount = 0;
7      
8        // Iterate through all numbers in the array
9        for (int num : nums) {
10            // Check if the number is even
11            // A number is even if its least significant bit is 0
12            // (num & 1) gives 0 for even numbers, 1 for odd numbers
13            // So ((num & 1) ^ 1) gives 1 for even numbers, 0 for odd numbers
14            evenCount += ((num & 1) ^ 1);
15        }
16      
17        // Return true if there are at least 2 even numbers
18        // (the bitwise OR of two even numbers will have a trailing zero)
19        return evenCount >= 2;
20    }
21};
22
1/**
2 * Checks if there exists at least one pair of elements in the array
3 * whose bitwise OR results in a number with trailing zeros (even number).
4 * This happens when we have at least 2 even numbers in the array.
5 * 
6 * @param nums - Array of integers to check
7 * @returns true if at least 2 even numbers exist, false otherwise
8 */
9function hasTrailingZeros(nums: number[]): boolean {
10    // Count the number of even numbers in the array
11    let evenCount: number = 0;
12  
13    // Iterate through each number in the array
14    for (const num of nums) {
15        // Check if the number is even by examining its least significant bit
16        // (num & 1) gives 0 for even numbers, 1 for odd numbers
17        // XOR with 1 flips the result: 1 for even, 0 for odd
18        evenCount += (num & 1) ^ 1;
19    }
20  
21    // Need at least 2 even numbers to create a bitwise OR with trailing zeros
22    return evenCount >= 2;
23}
24

Time and Space Complexity

The time complexity is O(n), where n is the length of the array nums. This is because the code iterates through each element in the array exactly once using a generator expression. For each element x, it performs a constant-time operation (x & 1 ^ 1) to check if the number is even (the expression evaluates to 1 if x is even, 0 if odd). The sum() function then accumulates these values, requiring a single pass through all n elements.

The space complexity is O(1). The generator expression (x & 1 ^ 1 for x in nums) doesn't create an intermediate list but instead yields values one at a time. The sum() function only maintains a single running total variable regardless of the input size, using constant extra space.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

Pitfall 1: Misunderstanding the XOR Operator Precedence

The Issue: Many developers might write the expression as x & 1 ^ 1 thinking it evaluates as (x & 1) ^ 1, but without parentheses, operator precedence could be confusing. In Python, both & and ^ have the same precedence level and are evaluated left-to-right, so this works correctly. However, this can lead to bugs when translating to other languages or when developers misread the intention.

Why It's Problematic:

  • In some languages, operator precedence differs
  • Code readability suffers when relying on implicit precedence
  • Future maintainers might misinterpret the logic

Solution:

# More explicit version with parentheses
even_count = sum((x & 1) ^ 1 for x in nums)

# Or even clearer: directly check if number is even
even_count = sum(1 for x in nums if x % 2 == 0)

Pitfall 2: Overcomplicating the Even Number Check

The Issue: Using (x & 1) ^ 1 to check for even numbers, while clever, is less intuitive than simpler alternatives. This bit manipulation might confuse team members unfamiliar with bitwise operations.

Why It's Problematic:

  • Reduces code maintainability
  • Takes longer to understand during code reviews
  • No performance benefit over simpler approaches

Solution:

class Solution:
    def hasTrailingZeros(self, nums: List[int]) -> bool:
        # Simple and clear approach
        even_count = 0
        for num in nums:
            if num % 2 == 0:  # Direct even check
                even_count += 1
                if even_count >= 2:  # Early termination
                    return True
        return False

Pitfall 3: Not Optimizing for Early Termination

The Issue: The original solution counts all even numbers in the array, even after finding 2 even numbers (which is sufficient to return True).

Why It's Problematic:

  • Unnecessary iterations when we already have our answer
  • In arrays with many elements, this wastes computational cycles

Solution:

class Solution:
    def hasTrailingZeros(self, nums: List[int]) -> bool:
        even_count = 0
        for num in nums:
            if num & 1 == 0:  # Check if even (LSB is 0)
                even_count += 1
                if even_count == 2:  # Return immediately when condition is met
                    return True
        return False

Pitfall 4: Misunderstanding the Problem Requirements

The Issue: Developers might incorrectly assume that ANY bitwise OR operation should have trailing zeros, rather than understanding that we need to SELECT specific elements whose OR has trailing zeros.

Why It's Problematic:

  • Could lead to checking if OR of ALL elements has trailing zeros
  • Might result in checking individual elements for trailing zeros

Solution: Ensure clear understanding that:

  • We SELECT a subset (2 or more elements)
  • We need the OR of ONLY even numbers to guarantee trailing zeros
  • The solution correctly identifies that having at least 2 even numbers is both necessary and sufficient
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

What are the most two important steps in writing a depth first search function? (Select 2)


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More