LeetCode in Kotlin

2411. Smallest Subarrays With Maximum Bitwise OR

Medium

You are given a 0-indexed array nums of length n, consisting of non-negative integers. For each index i from 0 to n - 1, you must determine the size of the minimum sized non-empty subarray of nums starting at i (inclusive) that has the maximum possible bitwise OR.

The bitwise OR of an array is the bitwise OR of all the numbers in it.

Return an integer array answer of size n where answer[i] is the length of the minimum sized subarray starting at i with maximum bitwise OR.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

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

Output: [3,3,2,2,1]

Explanation:

The maximum possible bitwise OR starting at any index is 3.

Therefore, we return [3,3,2,2,1].

Example 2:

Input: nums = [1,2]

Output: [2,1]

Explanation:

Starting at index 0, the shortest subarray that yields the maximum bitwise OR is of length 2.

Starting at index 1, the shortest subarray that yields the maximum bitwise OR is of length 1.

Therefore, we return [2,1].

Constraints:

Solution

class Solution {
    fun smallestSubarrays(nums: IntArray): IntArray {
        val res = IntArray(nums.size)
        val bitPosition = IntArray(30)
        for (i in nums.indices.reversed()) {
            res[i] = 1
            for (j in 0..29) {
                if (nums[i] and (1 shl j) > 0) {
                    bitPosition[j] = i
                }
                res[i] = res[i].coerceAtLeast(bitPosition[j] - i + 1)
            }
        }
        return res
    }
}