#446
Arithmetic Slices II - Subsequence
HardArrayDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal solution uses dynamic programming to count arithmetic subsequences efficiently. By maintaining a hashmap for each number to track the count of subsequences ending with that number and a specific difference, we avoid the combinatorial explosion of the brute-force method.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a list of hashmaps to store counts of subsequences for each number.
- 2Step 2: Iterate through each pair of numbers in the array to calculate the difference.
- 3Step 3: For each difference, update the hashmap for the current number based on the previous counts.
- 4Step 4: Sum the counts of valid subsequences that have at least three elements.
solution.py14 lines
1from collections import defaultdict
2
3def count_arithmetic_slices(nums):
4 n = len(nums)
5 dp = [defaultdict(int) for _ in range(n)]
6 count = 0
7
8 for i in range(n):
9 for j in range(i):
10 diff = nums[i] - nums[j]
11 count += dp[j][diff]
12 dp[i][diff] += dp[j][diff] + 1
13
14 return countℹ
Complexity note: The time complexity remains O(n²) due to the nested loops, but we efficiently track subsequences using hashmaps, which reduces the overhead of checking each subsequence. The space complexity is O(n) because we maintain a list of hashmaps for each number.
- 1Using hashmaps allows for efficient counting of subsequences.
- 2Recognizing arithmetic sequences can be reduced to tracking differences.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.