Longest Alternating Subarray — LeetCode 2765 Python Solution

EasyArrayEnumeration
Problem
#2765
Reading time
2 min

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 ans

Complexity

MeasureComplexity
TimeO(n^2), where n is the length of the array
SpaceO(1) auxiliary

Related problems

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview