2870. Longest Alternating Subarray
My accepted Python solution to LeetCode problem 2870, Longest Alternating Subarray, running in 59ms.
- Difficulty: Easy
- Python
- Runtime 59ms
- Memory 17.3MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 59ms, memory 17.3MB, accepted 2025-12-31.
class Solution:
def alternatingSubarray(self, nums: List[int]) -> int:
n = len(nums)
max_len = -1
for i in range(n - 1):
if nums[i + 1] - nums[i] == 1:
length = 2
expected = -1
j = i + 2
while j < n and nums[j] - nums[j - 1] == expected:
length += 1
expected *= -1
j += 1
max_len = max(max_len, length)
return max_len