Skip to content

Commit 3abb034

Browse files
committedApr 29, 2023
Runtime 2166 ms (Top 33.66%) | Memory 30.0 MB (Top 17.31%)
1 parent 5ae8225 commit 3abb034

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution:
2+
def smallestSubarrays(self, nums: List[int]) -> List[int]:
3+
# two sweeps
4+
len_n = len(nums)
5+
# sweep 1: find the maximum OR value at each index
6+
max_or = [0] * len_n
7+
idx, c_or = len_n - 1, 0
8+
while idx >= 0:
9+
c_or |= nums[idx]
10+
max_or[idx] = c_or
11+
idx -= 1
12+
13+
# sweep 2: starting from the last number, track the closest index for every bit
14+
ans = [1] * len_n
15+
bidx = [None] * 32
16+
idx = len_n - 1
17+
while idx >= 0:
18+
i = 0
19+
n = nums[idx]
20+
while n:
21+
if n & 1:
22+
bidx[i] = idx
23+
i += 1
24+
n >>= 1
25+
mor = max_or[idx]
26+
max_dist, i = 1, 0
27+
while mor:
28+
if mor & 1:
29+
max_dist = max(max_dist, bidx[i] - idx + 1)
30+
i += 1
31+
mor >>= 1
32+
ans[idx] = max_dist
33+
idx -= 1
34+
35+
return ans

0 commit comments

Comments
 (0)
Please sign in to comment.