Skip to content

Commit ae5188c

Browse files
committed
[LeetCode Sync] Runtime - 91 ms (61.40%), Memory - 33.6 MB (26.44%)
1 parent 3991b54 commit ae5188c

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers.</p>
2+
3+
<p>We call a subarray of <code>nums</code> <strong>nice</strong> if the bitwise <strong>AND</strong> of every pair of elements that are in <strong>different</strong> positions in the subarray is equal to <code>0</code>.</p>
4+
5+
<p>Return <em>the length of the <strong>longest</strong> nice subarray</em>.</p>
6+
7+
<p>A <strong>subarray</strong> is a <strong>contiguous</strong> part of an array.</p>
8+
9+
<p><strong>Note</strong> that subarrays of length <code>1</code> are always considered nice.</p>
10+
11+
<p>&nbsp;</p>
12+
<p><strong class="example">Example 1:</strong></p>
13+
14+
<pre>
15+
<strong>Input:</strong> nums = [1,3,8,48,10]
16+
<strong>Output:</strong> 3
17+
<strong>Explanation:</strong> The longest nice subarray is [3,8,48]. This subarray satisfies the conditions:
18+
- 3 AND 8 = 0.
19+
- 3 AND 48 = 0.
20+
- 8 AND 48 = 0.
21+
It can be proven that no longer nice subarray can be obtained, so we return 3.</pre>
22+
23+
<p><strong class="example">Example 2:</strong></p>
24+
25+
<pre>
26+
<strong>Input:</strong> nums = [3,1,5,11,13]
27+
<strong>Output:</strong> 1
28+
<strong>Explanation:</strong> The length of the longest nice subarray is 1. Any subarray of length 1 can be chosen.
29+
</pre>
30+
31+
<p>&nbsp;</p>
32+
<p><strong>Constraints:</strong></p>
33+
34+
<ul>
35+
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
36+
<li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
37+
</ul>
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution:
2+
def longestNiceSubarray(self, nums: list[int]) -> int:
3+
used_bits = 0 # Tracks bits used in current window
4+
window_start = 0 # Start position of current window
5+
max_length = 0 # Length of longest nice subarray found
6+
7+
for window_end in range(len(nums)):
8+
# If current number shares bits with window, shrink window from left
9+
# until there's no bit conflict
10+
while used_bits & nums[window_end] != 0:
11+
used_bits ^= nums[
12+
window_start
13+
] # Remove leftmost element's bits
14+
window_start += 1 # Shrink window from left
15+
16+
# Add current number to the window
17+
used_bits |= nums[window_end]
18+
19+
# Update max length if current window is longer
20+
max_length = max(max_length, window_end - window_start + 1)
21+
22+
return max_length

0 commit comments

Comments
 (0)