Construct Uniform Parity Array II Problem
Description
LeetCode Problem 3876.
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):
nums2[i] = nums1[i]nums2[i] = nums1[i] - nums1[j], for an indexj != i, such thatnums1[i] - nums1[j] >= 1
Return true if it is possible to construct such an array, otherwise return false.
Example 1:
Input: nums1 = [1,4,7]
Output: true
Explanation:
- Set nums2[0] = nums1[0] = 1.
- Set nums2[1] = nums1[1] - nums1[0] = 4 - 1 = 3.
- Set nums2[2] = nums1[2] = 7.
- nums2 = [1, 3, 7], and all elements are odd. Thus, the answer is true.
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:
- Set nums2[0] = nums1[0] = 4.
- Set nums2[1] = nums1[1] = 6.
- nums2 = [4, 6], and all elements are even. Thus, the answer is true.
Constraints:
1 <= n == nums1.length <= 10^51 <= nums1[i] <= 10^9nums1consists of distinct integers.
Solution
Approach: Brain Teaser
If all elements of nums1 have the same parity, take nums2 = nums1.
Otherwise both parities occur. The smallest odd number mn can never become even, because subtracting a smaller positive difference needs a smaller element to subtract, and an odd minus an even stays odd while an odd minus an odd needs a smaller odd number, which does not exist. So the target parity must be odd.
Every odd element can stay as it is. An even element x can become odd only by subtracting an odd y with y < x, and the best choice is mn. So the answer is false exactly when some even element is smaller than mn, and true otherwise.
Complexity: time O(n), space O(1), where n is the length of nums1.
class Solution:
def uniformArray(self, nums1: List[int]) -> bool:
mn = min((x for x in nums1 if x & 1), default=None)
return mn is None or all(x >= mn for x in nums1 if x & 1 == 0)