Taro Logo

Construct the Minimum Bitwise Array II

#2 Most AskedMedium
0 views
Topics:
ArraysBit Manipulation

You are given an array nums consisting of n prime integers.

You need to construct an array ans of length n, such that, for each index i, the bitwise OR of ans[i] and ans[i] + 1 is equal to nums[i], i.e. ans[i] OR (ans[i] + 1) == nums[i].

Additionally, you must minimize each value of ans[i] in the resulting array.

If it is not possible to find such a value for ans[i] that satisfies the condition, then set ans[i] = -1.

Example 1:

Input: nums = [2,3,5,7]

Output: [-1,1,4,3]

Explanation:

  • For i = 0, as there is no value for ans[0] that satisfies ans[0] OR (ans[0] + 1) = 2, so ans[0] = -1.
  • For i = 1, the smallest ans[1] that satisfies ans[1] OR (ans[1] + 1) = 3 is 1, because 1 OR (1 + 1) = 3.
  • For i = 2, the smallest ans[2] that satisfies ans[2] OR (ans[2] + 1) = 5 is 4, because 4 OR (4 + 1) = 5.
  • For i = 3, the smallest ans[3] that satisfies ans[3] OR (ans[3] + 1) = 7 is 3, because 3 OR (3 + 1) = 7.

Example 2:

Input: nums = [11,13,31]

Output: [9,12,15]

Explanation:

  • For i = 0, the smallest ans[0] that satisfies ans[0] OR (ans[0] + 1) = 11 is 9, because 9 OR (9 + 1) = 11.
  • For i = 1, the smallest ans[1] that satisfies ans[1] OR (ans[1] + 1) = 13 is 12, because 12 OR (12 + 1) = 13.
  • For i = 2, the smallest ans[2] that satisfies ans[2] OR (ans[2] + 1) = 31 is 15, because 15 OR (15 + 1) = 31.

Constraints:

  • 1 <= nums.length <= 100
  • 2 <= nums[i] <= 109
  • nums[i] is a prime number.

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 range of values for the elements in the `nums` array, and can any numbers be even?
  2. Since the problem states `nums` contains prime integers, is it guaranteed that all input integers will strictly be prime numbers greater than 2, given that 2 is the only even prime and has no valid answer?
  3. If no valid integer exists for a given value in `nums`, should the corresponding entry in `ans` be explicitly set to `-1`?
  4. Can the input array contain duplicate prime values, and if so, should they be processed independently or can we optimize with memoization?
  5. If multiple integers satisfy the condition for a given `nums[i]`, does the problem strictly require the absolute minimum possible integer?

Brute Force Solution

Approach

Imagine you are given a target number and you need to find a smaller starting number which, when combined with the number just one step larger, creates your target using a specific bitwise combination rule. The brute force approach simply tests every possible smaller number one by one to see which one works.

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

  1. Start by testing the very smallest possible number, which is zero.
  2. Check if combining this test number with the number one above it results in your target value.
  3. If it does, you have found a working solution and can stop right there.
  4. If it does not match, move on to the next larger whole number and test it.
  5. Repeat this checking process for every single number up to your target value, one after the other.
  6. If you happen to test every single possibility and none of them work, conclude that a valid answer does not exist for your target.

Code Implementation

def construct_min_bitwise_array(target_numbers):
    answer_list = []

    for target_value in target_numbers:
        found_solution = False

        # Test every possible starting number sequentially from zero up to the target value
        for test_number in range(target_value + 1):
            if (test_number | (test_number + 1)) == target_value:
                answer_list.append(test_number)
                found_solution = True
                break

        # If we exhausted all possibilities without success, record that no valid answer exists
        if not found_solution:
            answer_list.append(-1)

    return answer_list

Big(O) Analysis

Time Complexity
O(n * M) – For each of the n numbers in the input array, the brute force approach tests every potential starting number starting from zero up to the target value M. Since we check up to M possible values for each of the n elements, we perform up to n * M total checking operations in the worst-case scenario. This accumulation of checks across all elements results in approximately n * M operations, which simplifies to O(n * M) where M is the magnitude of the target values.
Space Complexity
O(N) – The algorithm builds an output array of size N to store the minimum starting number found for each of the N target values in the input list. Beyond this resulting array, the iterative searching process only utilizes a few scalar variables that take constant extra memory. Therefore, the total auxiliary space scales directly with the number of target elements, resulting in a linear space complexity of O(N).

Optimal Solution

Approach

Instead of testing every single number to find a match, we can use a clever shortcut based on how binary numbers work. By looking closely at the trailing ones in our target number, we can instantly figure out the smallest matching value without any guesswork.

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

  1. Examine the target number to check if it is an even number, because even numbers can never be formed by combining a number with itself plus one.
  2. If the number is even, immediately note that no valid answer exists and move on.
  3. For odd numbers, look at the very end of their binary representation to find the longest block of consecutive ones.
  4. Locate the specific one that sits right before this trailing block of ones.
  5. Flip that specific one to a zero to create our secret building block.
  6. Convert that modified building block back into a normal number and place it into our results.
  7. If a target number had no leading ones before the trailing block, realize that no valid building block can be formed and record that nothing works.
  8. Repeat this quick inspection for every target number to fill out the final results instantly.

Code Implementation

def min_bitwise_array(target_numbers):
    final_results = []

    for current_target in target_numbers:
        # Even numbers cannot be formed because any number plus itself plus one is odd.
        if current_target % 2 == 0:
            final_results.append(-1)
            continue

        trailing_ones_mask = (current_target & (current_target + 1))

        target_plus_one = current_target + 1

        lowest_trailing_bit = target_plus_one & -target_plus_one

        # Flipping the bit before the trailing ones block yields the minimum possible value.
        candidate_solution = current_target - (lowest_trailing_bit >> 1)

        final_results.append(candidate_solution)

    # Returning the complete array of minimum building blocks for all queries.
    return final_results

Big(O) Analysis

Time Complexity
O(n) – For each of the n elements in the target array, we perform constant-time bitwise operations to inspect the trailing ones and modify the bits. Because we only iterate through the input array once and execute a fixed number of arithmetic and bit manipulation steps per element, the total operations scale linearly with n. This results in roughly a constant factor multiplied by n operations, which simplifies directly to the final Big O time complexity.
Space Complexity
O(N) – To store the final results for every target number, the algorithm constructs an auxiliary output list that grows proportionally with the number of inputs. Here, N represents the total number of target elements provided in the input array. Aside from this output list, only a few primitive scalar variables are used to inspect the binary bits of each number, requiring negligible constant extra space. Therefore, the total auxiliary space complexity is driven entirely by the output collection, scaling linearly to O(N).

Edge Cases

Even prime number input such as 2
How to Handle:
Since 2 has no bitwise OR combination where ans OR (ans >> 1) equals 2, the algorithm correctly assigns negative one.
Prime numbers of the form 2^k - 1 such as 3, 7, 31
How to Handle:
The algorithm identifies the longest trailing sequence of ones and unsets the second-to-last one in that sequence to yield the minimum possible answer.
Prime numbers with alternating bits or single trailing one such as 5
How to Handle:
The algorithm detects the trailing bit pattern and clears the least significant set bit before the trailing zero block to satisfy the OR condition.
Maximum possible prime values fitting within 32-bit or 64-bit integer limits
How to Handle:
Bitwise operations are performed using standard integer types without overflow by leveraging efficient bit-shifting and masking techniques.
Single element array containing a prime number
How to Handle:
The iteration correctly processes the single element and returns a one-element array with the corresponding valid answer or negative one.
Array containing duplicate prime values
How to Handle:
Each element is processed independently in a loop, ensuring identical inputs yield identical correct outputs in the result array.
Large scale inputs with maximum allowed array length
How to Handle:
The solution operates in O(N) time complexity with O(1) extra space per element, easily scaling within standard execution time limits.
0/3 completed