LeetCode in Kotlin

3209. Number of Subarrays With AND Value of K

Hard

Given an array of integers nums and an integer k, return the number of subarrays of nums where the bitwise AND of the elements of the subarray equals k.

Example 1:

Input: nums = [1,1,1], k = 1

Output: 6

Explanation:

All subarrays contain only 1’s.

Example 2:

Input: nums = [1,1,2], k = 1

Output: 3

Explanation:

Subarrays having an AND value of 1 are: [**1**,1,2], [1,**1**,2], [**1,1**,2].

Example 3:

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

Output: 2

Explanation:

Subarrays having an AND value of 2 are: [1,**2**,3], [1,**2,3**].

Constraints:

Solution

class Solution {
    fun countSubarrays(nums: IntArray, k: Int): Long {
        var ans: Long = 0
        var left = 0
        var right = 0
        for (i in nums.indices) {
            val x = nums[i]
            var j = i - 1
            while (j >= 0 && (nums[j] and x) != nums[j]) {
                nums[j] = nums[j] and x
                j--
            }
            while (left <= i && nums[left] < k) {
                left++
            }
            while (right <= i && nums[right] <= k) {
                right++
            }
            ans += (right - left).toLong()
        }
        return ans
    }
}