2024-11-10 Daily Challenge
Today I have done leetcode's November LeetCoding Challenge with cpp
.
November LeetCoding Challenge 10
Description
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 of 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.
Example 1:
Input: nums = [1,2,3], k = 2
Output: 1
Explanation:
The subarray [3]
has OR
value of 3
. Hence, we return 1
.
Example 2:
Input: nums = [2,1,8], k = 10
Output: 3
Explanation:
The subarray [2,1,8]
has OR
value of 11
. Hence, we return 3
.
Example 3:
Input: nums = [1,2], k = 0
Output: 1
Explanation:
The subarray [1]
has OR
value of 1
. Hence, we return 1
.
Constraints:
1 <= nums.length <= 2 * 105
0 <= nums[i] <= 109
0 <= k <= 109
Solution
class Solution {
int k;
bitset<30> B;
void update(vector<int> &freq, unsigned x, bool add = true) {
bitset<30> b(x);
for(int i = 0; i < 30; ++i) {
freq[i] += add ? b[i] : -b[i];
}
}
bool check(vector<int> &freq) {
int b = 0;
for(int i = 0; i < 30; ++i) {
if(freq[i] > 0) b |= (1 << i);
}
return b >= k;
}
public:
int minimumSubarrayLength(vector<int>& nums, int k) {
if(!k) return 1;
this->k = k;
B = bitset<30>(k);
vector<int> freq(30);
int len = nums.size();
int answer = INT_MAX;
for(int begin = 0, end = 0; end < len; ++end) {
int x = nums[end];
if(x >= k) return 1;
update(freq, x);
while(begin < end && check(freq)) {
answer = min(answer, end - begin + 1);
update(freq, nums[begin], false);
begin += 1;
}
}
return answer == INT_MAX ? -1 : answer;
}
};