Longest Alternating Subarray — LeetCode 2765 Python Solution
EasyArrayEnumeration
- Problem
- #2765
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a 0-indexed integer array nums. A subarray s of length m is called alternating if: m is greater than 1.
Python solution
Python
class Solution:
def alternatingSubarray(self, nums: List[int]) -> int:
ans, n = -1, len(nums)
for i in range(n):
k = 1
j = i
while j + 1 < n and nums[j + 1] - nums[j] == k:
j += 1
k *= -1
if j - i + 1 > 1:
ans = max(ans, j - i + 1)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2), where n is the length of the array |
| Space | O(1) auxiliary |
Related problems
LeetCode 1534Count Good TripletsEasyLeetCode 1566Detect Pattern of Length M Repeated K or More TimesEasyLeetCode 1620Coordinate With Maximum Network QualityMediumLeetCode 2735Collecting ChocolatesMediumLeetCode 2778Sum of Squares of Special ElementsEasyLeetCode 2934Minimum Operations to Maximize Last Elements in ArraysMedium
Frequently asked questions
- How hard is LeetCode 2765. Longest Alternating Subarray?
- LeetCode 2765. Longest Alternating Subarray is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2765. Longest Alternating Subarray?
- The Python solution on this page runs in O(n^2), where n is the length of the array.
- What is the space complexity of LeetCode 2765. Longest Alternating Subarray?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2765. Longest Alternating Subarray cover?
- LeetCode 2765. Longest Alternating Subarray is tagged Array and Enumeration on LeetCode.