EasyNo. 2765
Longest Alternating Subarray — LeetCode 2765 Python Solution
- Topics
- Array, Enumeration
- 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
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
- Time
- O(n2)where n is the length of the array
- Space · auxiliary
- O(1)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1534 | Count Good Triplets | Easy |
| 1566 | Detect Pattern of Length M Repeated K or More Times | Easy |
| 1620 | Coordinate With Maximum Network Quality | Medium |
| 2735 | Collecting Chocolates | Medium |
| 2778 | Sum of Squares of Special Elements | Easy |
| 2934 | Minimum Operations to Maximize Last Elements in Arrays | Medium |
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(n2), 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.