← All problems

3876. Construct Uniform Parity Array II

MediumOpen on LeetCodeProblem statement

Problem Statement

3876. Construct Uniform Parity Array II

Medium


You are given an array nums1 of n distinct integers.

You want to construct another array nums2 of length n such that the elements in nums2 are either all odd or all even.

For each index i, you must choose exactly one of the following (in any order):

Return true if it is possible to construct such an array, otherwise return false.

 

Example 1:

Input: nums1 = [1,4,7]

Output: true

Explanation:​​​​​​​​​​​​​​

Example 2:

Input: nums1 = [2,3]

Output: false

Explanation:

It is not possible to construct nums2 such that all elements have the same parity. Thus, the answer is false.

Example 3:

Input: nums1 = [4,6]

Output: true

Explanation:

 

Constraints:

Java

Source file
class Solution {
    public boolean uniformArray(int[] nums1) {
        // Intuition: The minimum element in array must be odd,
        // that way it can reverse the parity of other even/odd elements
        // if its not odd, only viable condition is if entire array is even elems.
        int odd = 0, min = Integer.MAX_VALUE;
        for (int i : nums1) {
            if ((i & 1) == 1)
                odd++;
            min = Math.min(min, i);
        }
        if ((min & 1) == 1)
            return true;
        return odd == 0;
    }
}