diff --git a/kt/shortest-subarray-with-or-at-least-k-ii.kt b/kt/shortest-subarray-with-or-at-least-k-ii.kt new file mode 100644 index 0000000..ecfe498 --- /dev/null +++ b/kt/shortest-subarray-with-or-at-least-k-ii.kt @@ -0,0 +1,54 @@ +class Solution { + private data class Window(val bits: IntArray, var left: Int) { + fun updateBits( + number: Int, + d: Int, + ) = bits.indices + .filter { number.shr(it).and(1) != 0 } + .forEach { + bits[it] += d + } + + fun toInt(): Int = + bits + .mapIndexed { index, it -> + when { + it != 0 -> 1.shl(index) + else -> 0 + } + } + .reduce(Int::or) + + fun update( + nums: IntArray, + k: Int, + right: Int, + ): Int { + updateBits(nums[right], 1) + + var minLength = Int.MAX_VALUE + while (left <= right && toInt() >= k) { + minLength = listOf(minLength, right - left + 1).min() + + updateBits(nums[left], -1) + left += 1 + } + + return minLength + } + } + + fun minimumSubarrayLength( + nums: IntArray, + k: Int, + ): Int { + val window = Window(IntArray(32), 0) + + return nums.indices + .map { + window.update(nums, k, it) + } + .filter { it < Int.MAX_VALUE } + .minOrNull() ?: -1 + } +}