LeetCode in Kotlin

3917. Count Indices With Opposite Parity

Easy

You are given an integer array nums of length n.

The score of an index i is defined as the number of indices j such that:

Return an integer array answer of length n, where answer[i] is the score of index i.

Example 1:

Input: nums = [1,2,3,4]

Output: [2,1,1,0]

Explanation:

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:

Solution

class Solution {
    fun countOppositeParity(nums: IntArray): IntArray {
        val n = nums.size
        var odd = 0
        var even = 0
        val result = IntArray(n)
        for (i in n - 1 downTo 0) {
            if ((nums[i] and 1) == 1) {
                result[i] = even
                odd++
            } else {
                result[i] = odd
                even++
            }
        }
        return result
    }
}