Construct Uniform Parity Array I Problem
#3875
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3875.
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
Return true if it is possible to construct such an array, otherwise, return false.
Example 1:
Input: nums1 = [2,3]
Output: true
Explanation:
- Choose nums2[0] = nums1[0] - nums1[1] = 2 - 3 = -1.
- Choose nums2[1] = nums1[1] = 3.
- nums2 = [-1, 3], and both elements are odd. Thus, the answer is true.
Example 2:
Input: nums1 = [4,6]
Output: true
Explanation:
- Choose nums2[0] = nums1[0] = 4.
- Choose nums2[1] = nums1[1] = 6.
- nums2 = [4, 6], and all elements are even. Thus, the answer is true.
Constraints:
1 <= n == nums1.length <= 1001 <= nums1[i] <= 100nums1consists of distinct integers.
Solution
Approach: Brain Teaser
If every element of nums1 has the same parity, take nums2 = nums1.
If both parities occur, replace every element by itself minus some element of the opposite parity. An odd minus an even and an even minus an odd are both odd, so every element of nums2 is odd.
So a valid nums2 always exists and the answer is true.
Complexity: time O(1), space O(1).
class Solution:
def uniformArray(self, nums1: List[int]) -> bool:
return True