From 97b79b8025b7eaab84355189110037b4a5e1eee5 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 10 Nov 2024 19:16:43 +0100 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB3097.=20Shortest=20Subarray?= =?UTF-8?q?=20With=20OR=20at=20Least=20K=20II=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/shortest-subarray-with-or-at-least-k-ii/ Signed-off-by: Matej Focko --- kt/shortest-subarray-with-or-at-least-k-ii.kt | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 kt/shortest-subarray-with-or-at-least-k-ii.kt 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 + } +}