Skip to content

Commit 2b30647

Browse files
committed
Sync LeetCode submission Runtime - 92 ms (55.49%), Memory - 33.6 MB (26.22%)
1 parent b0c50a3 commit 2b30647

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

2478-longest-nice-subarray/README.md

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: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Approach 2: Sliding Window
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def longestNiceSubarray(self, nums: List[int]) -> int:
8+
used_bits = 0 # Track bits used in current window
9+
window_start = 0
10+
max_length = 0
11+
12+
for window_end in range(len(nums)):
13+
# If current number shares bits with window, shrink window from left until there's no bit conflict
14+
while used_bits & nums[window_end] != 0:
15+
used_bits ^= nums[window_start] # Remove leftmost element's bits
16+
window_start += 1
17+
18+
# Add current number to window
19+
used_bits |= nums[window_end]
20+
21+
max_length = max(max_length, window_end - window_start + 1)
22+
23+
return max_length
24+
25+

0 commit comments

Comments
 (0)