#3875
Construct Uniform Parity Array I
EasyArrayMathHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
To construct a uniform parity array, we can leverage the fact that the difference between any two distinct integers will always yield an odd or even result based on their parities. If we have at least one even and one odd number, we can always create a uniform array.
⚙️
Algorithm
3 steps- 1Step 1: Count the number of even and odd integers in nums1.
- 2Step 2: If there are at least one even and one odd integer, return true.
- 3Step 3: If all integers are even or all are odd, return true.
solution.py4 lines
1def canConstruct(nums1):
2 evens = sum(1 for x in nums1 if x % 2 == 0)
3 odds = len(nums1) - evens
4 return evens == 0 or odds == 0ℹ
Complexity note: The complexity is O(n) because we only need to traverse the array once to count evens and odds.
- 1Parity of numbers determines the possibility of uniformity.
- 2The difference between two numbers affects the resulting parity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.