#413
Arithmetic Slices
MediumArrayDynamic ProgrammingSliding WindowDynamic ProgrammingSliding Window
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)
Instead of checking every subarray, we can keep track of the number of valid arithmetic slices ending at each index. This allows us to count slices in linear time.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable to keep track of the current count of arithmetic slices.
- 2Step 2: Iterate through the array starting from the third element.
- 3Step 3: If the current element and the previous two elements form an arithmetic sequence, increment the current count and add it to the total count.
solution.py11 lines
1def count_arithmetic_slices(nums):
2 count = 0
3 current = 0
4 n = len(nums)
5 for i in range(2, n):
6 if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]:
7 current += 1
8 count += current
9 else:
10 current = 0
11 return countℹ
Complexity note: This complexity is linear because we only traverse the array once, keeping track of the current count of arithmetic slices.
- 1Arithmetic slices must have at least three elements.
- 2The difference between consecutive elements must be constant.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.