Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit f094b28

Browse files
committed
Add solution #3097
1 parent 62a53f1 commit f094b28

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2167,6 +2167,7 @@
21672167
3090|[Maximum Length Substring With Two Occurrences](./solutions/3090-maximum-length-substring-with-two-occurrences.js)|Easy|
21682168
3091|[Apply Operations to Make Sum of Array Greater Than or Equal to k](./solutions/3091-apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k.js)|Medium|
21692169
3095|[Shortest Subarray With OR at Least K I](./solutions/3095-shortest-subarray-with-or-at-least-k-i.js)|Easy|
2170+
3097|[Shortest Subarray With OR at Least K II](./solutions/3097-shortest-subarray-with-or-at-least-k-ii.js)|Medium|
21702171
3105|[Longest Strictly Increasing or Strictly Decreasing Subarray](./solutions/3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js)|Easy|
21712172
3108|[Minimum Cost Walk in Weighted Graph](./solutions/3108-minimum-cost-walk-in-weighted-graph.js)|Hard|
21722173
3110|[Score of a String](./solutions/3110-score-of-a-string.js)|Easy|
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* 3097. Shortest Subarray With OR at Least K II
3+
* https://leetcode.com/problems/shortest-subarray-with-or-at-least-k-ii/
4+
* Difficulty: Medium
5+
*
6+
* You are given an array nums of non-negative integers and an integer k.
7+
*
8+
* An array is called special if the bitwise OR of all of its elements is at least k.
9+
*
10+
* Return the length of the shortest special non-empty subarray of nums, or return -1 if no
11+
* special subarray exists.
12+
*/
13+
14+
/**
15+
* @param {number[]} nums
16+
* @param {number} k
17+
* @return {number}
18+
*/
19+
var minimumSubarrayLength = function(nums, k) {
20+
if (k === 0) return 1;
21+
22+
const bitCounts = new Array(32).fill(0);
23+
let minLength = Infinity;
24+
let orValue = 0;
25+
let left = 0;
26+
27+
for (let right = 0; right < nums.length; right++) {
28+
const num = nums[right];
29+
for (let bit = 0; bit < 32; bit++) {
30+
if (num & (1 << bit)) bitCounts[bit]++;
31+
if (bitCounts[bit] > 0) orValue |= 1 << bit;
32+
}
33+
34+
while (orValue >= k && left <= right) {
35+
minLength = Math.min(minLength, right - left + 1);
36+
const leftNum = nums[left];
37+
for (let bit = 0; bit < 32; bit++) {
38+
if (leftNum & (1 << bit)) {
39+
bitCounts[bit]--;
40+
if (bitCounts[bit] === 0) orValue &= ~(1 << bit);
41+
}
42+
}
43+
left++;
44+
}
45+
}
46+
47+
return minLength === Infinity ? -1 : minLength;
48+
};

0 commit comments

Comments
 (0)