aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--shortest_subarr_or_k2.c35
-rw-r--r--shortest_subarr_or_k2.py40
2 files changed, 75 insertions, 0 deletions
diff --git a/shortest_subarr_or_k2.c b/shortest_subarr_or_k2.c
new file mode 100644
index 0000000..b6b81e9
--- /dev/null
+++ b/shortest_subarr_or_k2.c
@@ -0,0 +1,35 @@
+// 3097. Shortest Subarray With OR at Least K II
+#include "leetcode.h"
+
+/*
+ * you are given an array 'nums' of non-negative integers and an integer 'k'. an
+ * array is called special if the bitwise OR of all its elements is at least
+ * 'k'. return the length of the shortest special non-empty subarray of 'nums',
+ * or return -1 if no special subarray exists.
+ */
+
+int minimumSubarrayLength(int *nums, int numsSize, int k) {
+ int cnt[30] = {}, curr = 0, ans = INT_MAX;
+ for (int i = 0, j = 0; i < numsSize; ++i) {
+ for (int b = 0; b < 30; ++b)
+ if ((1 << b) & nums[i])
+ if (++cnt[b] == 1)
+ curr += (1 << b);
+ while (curr >= k && j <= i) {
+ ans = fmin(ans, i - j + 1);
+ for (int b = 0; b < 30; ++b)
+ if ((1 << b) & nums[j])
+ if (!(--cnt[b]))
+ curr -= (1 << b);
+ ++j;
+ }
+ }
+ return ans == INT_MAX ? -1 : ans;
+}
+
+int main() {
+ int n1[] = {1, 2, 3}, n2[] = {2, 1, 8}, n3[] = {1, 2};
+ printf("%d\n", minimumSubarrayLength(n1, ARRAY_SIZE(n1), 2)); // expect: 1
+ printf("%d\n", minimumSubarrayLength(n2, ARRAY_SIZE(n2), 10)); // expect: 3
+ printf("%d\n", minimumSubarrayLength(n3, ARRAY_SIZE(n3), 0)); // expect: 1
+}
diff --git a/shortest_subarr_or_k2.py b/shortest_subarr_or_k2.py
new file mode 100644
index 0000000..6a85059
--- /dev/null
+++ b/shortest_subarr_or_k2.py
@@ -0,0 +1,40 @@
+# 3097. Shortest Subarray With OR at Least K II
+
+"""
+you are given an array 'nums' of non-negative integers and an integer 'k'. an
+array is called special if the bitwise OR of all its elements is at least
+'k'. return the length of the shortest special non-empty subarray of 'nums',
+or return -1 if no special subarray exists.
+"""
+
+
+class Solution(object):
+ def minimumSubarrayLength(self, nums, k):
+ """
+ :type nums: List[int]
+ :type k: int
+ :rtype: int
+ """
+ cnt = [0 for _ in range(32)]
+ n, j, curr, ans = len(nums), 0, 0, float("inf")
+ for i in range(n):
+ curr |= nums[i]
+ for b in range(32):
+ if nums[i] & 1 << b:
+ cnt[b] += 1
+ while curr >= k and j <= i:
+ ans = min(ans, i - j + 1)
+ for b in range(32):
+ if nums[j] & 1 << b:
+ cnt[b] -= 1
+ if not cnt[b]:
+ curr ^= 1 << b
+ j += 1
+ return ans if ans != float("inf") else -1
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.minimumSubarrayLength(nums=[1, 2, 3], k=2))
+ print(obj.minimumSubarrayLength(nums=[2, 1, 8], k=10))
+ print(obj.minimumSubarrayLength(nums=[1, 2], k=0))