↓Skip to main content
  1. LeetCode/

LeetCode 3917: Count Indices With Opposite Parity

·1 min· ·
LeetCode Easy Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2026-05-03

  • Submissions: Accepted (first try)

Approach
#

For each i, count the j to its right with parity opposite to nums[i]. Scan right to left keeping “how many evens and odds are to the right” (Array Template 3); each position reads the opposite count directly, then adds itself.

My Solution
#

class Solution:
    def countOppositeParity(self, nums: List[int]) -> List[int]:
        seen = [0, 0]                          # 右邊的偶數、奇數個數
        res = [0] * len(nums)
        for i in range(len(nums) - 1, -1, -1):
            p = nums[i] % 2
            res[i] = seen[1 - p]
            seen[p] += 1
        return res

I originally rescanned to the right for every i, O(n²); the small range let it pass.

Complexity
#

Time O(n), space O(n) for the output.

Mistakes to Avoid
#

  • The count is of elements to the right, so scan right to left, reading the answer before adding the element itself.

Interview Explanation
#

Scanning right to left, I keep how many evens and odds are to the right; each position’s answer is the opposite-parity count, then it adds itself. Time O(n).

Related

LeetCode 3912: Valid Elements in an Array
·2 mins
LeetCode Easy Array
LeetCode 3912 note: greater than all on the left means greater than the prefix maximum, and likewise for the right with the suffix maximum; scan both ways and output in original order
LeetCode 3903: Smallest Stable Index I
·1 min
LeetCode Easy Prefix-Sum Array
LeetCode 3903 note: the first index where the prefix maximum minus the suffix minimum is <= k; build the suffix minimum right to left first
LeetCode 3898: Find the Degree of Each Vertex
·1 min
LeetCode Easy Graph Matrix Array
LeetCode 3898 note: the number of ones in row i of the adjacency matrix is vertex i’s degree
LeetCode 3838: Weighted Word Mapping
·1 min
LeetCode Easy Array String Simulation
LeetCode 3838 note: sum each word’s letter weights mod 26 and map backward: 0 -> z, i.e. chr(ord(‘z’) - r)
LeetCode 3379: Transformed Array
·1 min
LeetCode Easy Array Simulation
LeetCode 3379 note: moving nums[i] steps right or left is nums[(i + nums[i]) % n]; Python’s % returns a non-negative result for negatives too
LeetCode 2540: Minimum Common Value
·2 mins
LeetCode Easy Two-Pointers Array
LeetCode 2540 note: one pointer per sorted array, advance the smaller side, and the first match is the answer