#3876
Construct Uniform Parity Array II
MediumArrayMathHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
To construct nums2, we can fix the parity to either all odd or all even. By using the smallest odd/even element for subtraction, we can ensure all elements match the desired parity.
⚙️
Algorithm
3 steps- 1Step 1: Identify the smallest odd and even numbers in nums1.
- 2Step 2: Check if we can create an all-odd array using the smallest even number for subtraction or vice versa.
- 3Step 3: Return true if either condition is satisfied.
solution.py6 lines
1def canConstruct(nums1):
2 odds = [x for x in nums1 if x % 2 != 0]
3 evens = [x for x in nums1 if x % 2 == 0]
4 if odds and (min(odds) - min(evens) >= 1): return True
5 if evens and (min(evens) - min(odds) >= 1): return True
6 return Falseℹ
Complexity note: Single pass to classify numbers into odds and evens, leading to linear time complexity.
- 1Identify smallest odd/even for parity adjustments.
- 2Uniform parity can be achieved through careful selection.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.