All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g2501_2600.s2568_minimum_impossible_or.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g2501_2600.s2568_minimum_impossible_or;

// #Medium #Array #Bit_Manipulation #Brainteaser
// #2023_08_21_Time_14_ms_(81.48%)_Space_62.4_MB_(6.17%)

import java.util.HashSet;
import java.util.Set;

/**
 * 2568 - Minimum Impossible OR\.
 *
 * Medium
 *
 * You are given a **0-indexed** integer array `nums`.
 *
 * We say that an integer x is **expressible** from `nums` if there exist some integers 0 <= index1 < index2 < ... < indexk < nums.length for which nums[index1] | nums[index2] | ... | nums[indexk] = x. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of `nums`.
 *
 * Return _the minimum **positive non-zero integer** that is not_ _expressible from_ `nums`.
 *
 * **Example 1:**
 *
 * **Input:** nums = [2,1]
 *
 * **Output:** 4
 *
 * **Explanation:** 1 and 2 are already present in the array. We know that 3 is expressible, since nums[0] | nums[1] = 2 | 1 = 3. Since 4 is not expressible, we return 4.
 *
 * **Example 2:**
 *
 * **Input:** nums = [5,3,2]
 *
 * **Output:** 1
 *
 * **Explanation:** We can show that 1 is the smallest number that is not expressible.
 *
 * **Constraints:**
 *
 * *   1 <= nums.length <= 105
 * *   1 <= nums[i] <= 109
**/
public class Solution {
    public int minImpossibleOR(int[] nums) {
        Set set = new HashSet<>();
        for (int n : nums) {
            if (n == 1 || (n & 1) == 0) {
                set.add(n);
            }
        }
        int powerOfTwo = 1;
        while (true) {
            if (!set.contains(powerOfTwo)) {
                return powerOfTwo;
            }
            powerOfTwo *= 2;
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy