Taro Logo

Check if Bitwise OR Has Trailing Zeros

Easy
Asked by:
Meituan
0 views
Topics:
ArraysBit Manipulation

You are given an array of positive integers nums.

You have to check if it is possible to select two or more elements in the array such that the bitwise OR of the selected elements has at least one trailing zero in its binary representation.

For example, the binary representation of 5, which is "101", does not have any trailing zeros, whereas the binary representation of 4, which is "100", has two trailing zeros.

Return true if it is possible to select two or more elements whose bitwise OR has trailing zeros, return false otherwise.

Example 1:

Input: nums = [1,2,3,4,5]
Output: true
Explanation: If we select the elements 2 and 4, their bitwise OR is 6, which has the binary representation "110" with one trailing zero.

Example 2:

Input: nums = [2,4,8,16]
Output: true
Explanation: If we select the elements 2 and 4, their bitwise OR is 6, which has the binary representation "110" with one trailing zero.
Other possible ways to select elements to have trailing zeroes in the binary representation of their bitwise OR are: (2, 8), (2, 16), (4, 8), (4, 16), (8, 16), (2, 4, 8), (2, 4, 16), (2, 8, 16), (4, 8, 16), and (2, 4, 8, 16).

Example 3:

Input: nums = [1,3,5,7,9]
Output: false
Explanation: There is no possible way to select two or more elements to have trailing zeros in the binary representation of their bitwise OR.

Constraints:

  • 2 <= nums.length <= 100
  • 1 <= nums[i] <= 100

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the minimum and maximum size of the input array `nums`?
  2. Are all integers in the array guaranteed to be strictly positive, or could there be zeros or negative numbers?
  3. Does selecting 'at least two elements' mean we need to pick two distinct indices from the array, or can we pick the same element twice if its value is duplicated?
  4. If multiple valid pairs exist, does it matter which pair we use to determine the boolean result?
  5. What is the exact definition of trailing zeros in this context? Does a binary representation like '10' (which has one trailing zero) qualify, and does the result need to have *at least* one trailing zero (i.e., being even)?

Brute Force Solution

Approach

Imagine you have a collection of numbers and want to find out if you can pick at least two of them whose combination ends with a zero in binary form. The brute force strategy relies on testing every single pair of numbers possible to see if any pair meets this requirement.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the entire collection of numbers provided to you.
  2. Pick the first number from the collection to be the first part of a pair.
  3. Pair this first number with every other number in the collection one by one.
  4. For each pair you form, combine them together using the specific rule given in the problem to see the resulting value.
  5. Check the resulting combined value to see if its binary representation ends with a zero.
  6. If you find any pair that produces a combined value ending with a zero, you have successfully answered the question.
  7. If the current pair does not work, move on to the next possible pair and repeat the combination and checking process.
  8. Continue testing every possible combination of pairs until you either find a successful pair or run out of pairs to try.

Code Implementation

def has_trailing_zeros(numbers_collection):
    # We test every possible pair because the brute force strategy requires checking all combinations
    for first_index in range(len(numbers_collection)):
        for second_index in range(first_index + 1, len(numbers_collection)):
            combined_value = numbers_collection[first_index] | numbers_collection[second_index]

            # We check the least significant bit because a trailing zero in binary means the number is even
            if (combined_value & 1) == 0:
                return True

    # If all pairs are exhausted without success, no valid pair exists in the collection
    return False

Big(O) Analysis

Time Complexity
O(n²) – For each of the n numbers in the collection, the strategy pairs it with every other remaining number to test the bitwise OR combination. For the first number we check n-1 other numbers, for the second we check n-2, and we continue this process until all pairs are evaluated. This nested evaluation of every possible unique pair requires approximately n * n/2 operations, which simplifies to the final time complexity of O(n²).
Space Complexity
O(1) – The algorithm only requires a few constant-sized primitive variables to keep track of the iteration indices and the pair evaluations. No auxiliary data structures, temporary lists, or recursive call stacks are utilized during the execution. Therefore, the extra memory used remains constant regardless of the input size N, where N is the total number of elements in the collection.

Optimal Solution

Approach

Instead of testing every possible combination of numbers, the clever shortcut is to focus on a very specific feature of numbers that have trailing zeros in their binary form. Specifically, we only need to look at how many even numbers are present in the collection.

Here's how the algorithm would work step-by-step:

  1. Think about how numbers are represented in binary and what creates a trailing zero when combining them using bitwise operations.
  2. Realize that a trailing zero in the final result means the combined value must be even, which strictly depends on both combined parts being even.
  3. Count how many even numbers appear in the entire collection from the very beginning.
  4. Check if you can find at least two even numbers anywhere in the collection.
  5. If you find at least two even numbers, combining any two of them will guarantee a trailing zero in the final result.
  6. If you find fewer than two even numbers, it is impossible to get a trailing zero, so you can immediately conclude it cannot be done.
  7. By simply counting the even numbers instead of testing combinations, you arrive at the correct answer instantly.

Code Implementation

def has_trailing_zeros(integer_collection):
    # We need to count even numbers because only they can contribute to trailing zeros.
    even_number_count = 0

    for current_number in integer_collection:
        if current_number % 2 == 0:
            even_number_count += 1

    # At least two even numbers are required to guarantee a trailing zero in the bitwise OR result.
    return even_number_count >= 2

Big(O) Analysis

Time Complexity
O(n) – To determine if we can form a bitwise OR with trailing zeros, we iterate through the collection of n numbers to count how many even integers are present. We examine each of the n elements exactly once in a single pass to check its parity without needing nested loops or testing every possible combination. The total number of operations scales linearly with the size of the input collection, which approximates to n operations in total. Simplifying this linear progression based on the input size n results in a final time complexity of O(n).
Space Complexity
O(1) – To determine if the bitwise OR has trailing zeros, the algorithm only needs to maintain a single counter variable to keep track of the number of even numbers encountered so far. This counter requires a constant amount of extra memory regardless of the input size, meaning no additional data structures like temporary lists or hash maps are created. As the input size N grows, the auxiliary space remains entirely static. Therefore, the total extra memory usage simplifies to Big O of 1.

Edge Cases

Array with exactly two elements
How to Handle:
The algorithm checks this single pair directly and returns true if their bitwise OR has a trailing zero.
Numbers with no even integers in the array
How to Handle:
Since trailing zeros in binary require an even number, the loop counts even numbers and returns false if the count is less than two.
Array containing all even numbers
How to Handle:
Any two even numbers end in zero, so their bitwise OR will also end in zero and immediately return true.
Array with a mix of odd and even numbers where only one even number exists
How to Handle:
Since selecting at least two elements is required and the OR of an odd and even number is odd, the solution correctly returns false.
Maximum-sized inputs with up to 100 elements
How to Handle:
An O(N squared) nested loop approach runs well within time limits for such small constraints.
Large integer values up to the constraint limit
How to Handle:
Standard 32-bit or 64-bit integers handle bitwise operations safely without any risk of overflow.
Array containing duplicate values
How to Handle:
Duplicate even numbers naturally provide the necessary pair with trailing zeros, causing the algorithm to return true.