#1630
Arithmetic Subarrays
MediumArrayHash TableSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n² log n) | O(n log n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution leverages the fact that a sorted sequence can be checked for arithmetic properties more efficiently. By sorting the subarray and checking the differences in one pass, we reduce the overall complexity significantly.
⚙️
Algorithm
5 steps- 1Step 1: For each query, extract the subarray defined by the indices l[i] and r[i].
- 2Step 2: Sort the extracted subarray.
- 3Step 3: Calculate the common difference using the first two elements.
- 4Step 4: Use a single loop to check if all consecutive differences are equal to the common difference.
- 5Step 5: Append the result to the answer list.
solution.py8 lines
1def checkArithmeticSubarrays(nums, l, r):
2 answer = []
3 for start, end in zip(l, r):
4 subarray = sorted(nums[start:end + 1])
5 diff = subarray[1] - subarray[0]
6 is_arithmetic = all(subarray[i + 1] - subarray[i] == diff for i in range(1, len(subarray) - 1))
7 answer.append(is_arithmetic)
8 return answerℹ
Complexity note: The time complexity is O(n log n) due to sorting the subarray, while the space complexity remains O(n) for storing the subarray.
- 1Sorting the subarray is essential to easily check for arithmetic properties.
- 2The common difference must remain consistent across the entire sorted subarray.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.