LeetCode in Kotlin

3152. Special Array II

Medium

An array is considered special if every pair of its adjacent elements contains two numbers with different parity.

You are given an array of integer nums and a 2D integer matrix queries, where for queries[i] = [fromi, toi] your task is to check that subarray nums[fromi..toi] is special or not.

Return an array of booleans answer such that answer[i] is true if nums[fromi..toi] is special.

Example 1:

Input: nums = [3,4,1,2,6], queries = [[0,4]]

Output: [false]

Explanation:

The subarray is [3,4,1,2,6]. 2 and 6 are both even.

Example 2:

Input: nums = [4,3,1,6], queries = [[0,2],[2,3]]

Output: [false,true]

Explanation:

  1. The subarray is [4,3,1]. 3 and 1 are both odd. So the answer to this query is false.
  2. The subarray is [1,6]. There is only one pair: (1,6) and it contains numbers with different parity. So the answer to this query is true.

Constraints:

Solution

class Solution {
    fun isArraySpecial(nums: IntArray, queries: Array<IntArray>): BooleanArray {
        val n = nums.size
        val bad = IntArray(n)
        for (i in 1 until n) {
            bad[i] = bad[i - 1] + (((nums[i - 1] xor nums[i]) and 1) xor 1)
        }
        val nq = queries.size
        val res = BooleanArray(nq)
        for (i in 0 until nq) {
            val q = queries[i]
            res[i] = calc(bad, q[0], q[1]) == 0
        }
        return res
    }

    private fun calc(arr: IntArray, st: Int, end: Int): Int {
        return arr[end] - arr[st]
    }
}