Difficulty: Easy | Acceptance: 81.50% | Paid: No Topics: N/A
You are given a 0-indexed integer array nums. An index i is called good if nums[i] and i have opposite parity. Return the number of good indices.
- Examples
- Constraints
- Approach 1: Linear Iteration
- Approach 2: Functional Programming
Examples
Example 1
Input:
nums = [1,2,3,4]
Output:
[2,1,1,0]
Explanation: nums[0] = 1, which is odd. Thus, the indices j = 1 and j = 3 satisfy the conditions, so the score of index 0 is 2.
nums[1] = 2, which is even. Thus, the index j = 2 satisfies the conditions, so the score of index 1 is 1.
nums[2] = 3, which is odd. Thus, the index j = 3 satisfies the conditions, so the score of index 2 is 1.
nums[3] = 4, which is even. Thus, no index satisfies the conditions, so the score of index 3 is 0.
Thus, the answer = [2, 1, 1, 0].
Example 2
Input:
nums = [1]
Output:
[0]
Explanation: There is only one element in nums. Thus, the score of index 0 is 0.
Constraints
1 <= nums.length <= 100
1 <= nums[i] <= 100
Approach 1: Linear Iteration
Intuition We iterate through the array once. For each index, we check if the parity of the index (even/odd) is different from the parity of the value at that index.
Steps
- Initialize a counter to 0.
- Loop through the array using the index
i. - Check if
(i % 2)is not equal to(nums[i] % 2). - If they are different, increment the counter.
- Return the counter.
class Solution:
def countOppositeParity(self, nums: list[int]) -> int:
count = 0
for i, val in enumerate(nums):
if (i % 2) != (val % 2):
count += 1
return countComplexity
- Time: O(n), where n is the length of the array.
- Space: O(1), as we only use a single variable for counting.
- Notes: This is the most efficient approach with minimal overhead.
Approach 2: Functional Programming
Intuition
We can use built-in functional methods like filter, reduce, or list comprehensions to condense the logic into a single expression, improving readability for those familiar with functional styles.
Steps
- Use a method that iterates over the array with access to the index (e.g.,
reducein JavaScript, list comprehension in Python). - Apply the parity check
(i % 2) != (val % 2). - Sum the number of times the condition is true.
class Solution:
def countOppositeParity(self, nums: list[int]) -> int:
return sum(1 for i, val in enumerate(nums) if (i % 2) != (val % 2))Complexity
- Time: O(n), as we must visit every element once.
- Space: O(1) auxiliary space, though some languages may create intermediate objects (like streams) depending on implementation.
- Notes: More concise but may have slight constant-time overhead compared to a raw loop.