#2765
Longest Alternating Subarray
EasyArrayEnumerationArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach leverages a single pass through the array to count the length of valid alternating subarrays. This is efficient because we only need to check adjacent elements once.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a variable to keep track of the current length of the alternating subarray and a maximum length variable.
- 2Step 2: Loop through the array starting from the second element.
- 3Step 3: For each element, check if it alternates with the previous one. If it does, increment the current length; otherwise, reset it.
- 4Step 4: Update the maximum length if the current length exceeds it.
- 5Step 5: Return the maximum length found, or -1 if no valid subarray exists.
solution.py12 lines
1def longestAlternatingSubarray(nums):
2 max_length = -1
3 current_length = 0
4 n = len(nums)
5 for i in range(1, n):
6 if nums[i] == nums[i - 1] + 1 or nums[i] == nums[i - 1] - 1:
7 current_length += 1
8 if current_length > 0:
9 max_length = max(max_length, current_length + 1)
10 else:
11 current_length = 0
12 return max_length if max_length > 1 else -1ℹ
Complexity note: The time complexity is O(n) because we only pass through the array once. The space complexity is O(1) since we only use a few variables for tracking lengths.
- 1The alternating pattern can be identified by checking the difference between adjacent elements.
- 2The problem can be solved efficiently with a single pass through the array.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.