Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
Given an integer array nums, return the number of all the arithmetic subsequences of nums.
A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
[1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences.[1, 1, 2, 5, 7] is not an arithmetic sequence.A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
[2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].The test cases are generated so that the answer fits in 32-bit integer.
Example 1:
Input: nums = [2,4,6,8,10] Output: 7 Explanation: All arithmetic subsequence slices are: [2,4,6] [4,6,8] [6,8,10] [2,4,6,8] [4,6,8,10] [2,4,6,8,10] [2,6,10]
Example 2:
Input: nums = [7,7,7,7,7] Output: 16 Explanation: Any subsequence of this array is arithmetic.
Constraints:
1 <= nums.length <= 1000-231 <= nums[i] <= 231 - 1Problem summary: Given an integer array nums, return the number of all the arithmetic subsequences of nums. A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences. For example, [1, 1, 2, 5, 7] is not an arithmetic sequence. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10]. The test cases are generated so that the answer fits in 32-bit integer.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming
[2,4,6,8,10]
[7,7,7,7,7]
arithmetic-slices)destroy-sequential-targets)count-palindromic-subsequences)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #446: Arithmetic Slices II - Subsequence
class Solution {
public int numberOfArithmeticSlices(int[] nums) {
int n = nums.length;
Map<Long, Integer>[] f = new Map[n];
Arrays.setAll(f, k -> new HashMap<>());
int ans = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < i; ++j) {
Long d = 1L * nums[i] - nums[j];
int cnt = f[j].getOrDefault(d, 0);
ans += cnt;
f[i].merge(d, cnt + 1, Integer::sum);
}
}
return ans;
}
}
// Accepted solution for LeetCode #446: Arithmetic Slices II - Subsequence
func numberOfArithmeticSlices(nums []int) (ans int) {
f := make([]map[int]int, len(nums))
for i := range f {
f[i] = map[int]int{}
}
for i, x := range nums {
for j, y := range nums[:i] {
d := x - y
cnt := f[j][d]
ans += cnt
f[i][d] += cnt + 1
}
}
return
}
# Accepted solution for LeetCode #446: Arithmetic Slices II - Subsequence
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
f = [defaultdict(int) for _ in nums]
ans = 0
for i, x in enumerate(nums):
for j, y in enumerate(nums[:i]):
d = x - y
ans += f[j][d]
f[i][d] += f[j][d] + 1
return ans
// Accepted solution for LeetCode #446: Arithmetic Slices II - Subsequence
struct Solution;
use std::collections::HashMap;
impl Solution {
fn number_of_arithmetic_slices(a: Vec<i32>) -> i32 {
let n = a.len();
let mut dp: HashMap<(usize, i64), usize> = HashMap::new();
let mut res = 0;
for i in 0..n {
for j in 0..i {
let diff = a[i] as i64 - a[j] as i64;
let prev = *dp.entry((j, diff)).or_insert(1);
res += prev - 1;
*dp.entry((i, diff)).or_insert(1) += prev;
}
}
res as i32
}
}
#[test]
fn test() {
let a = vec![2, 4, 6, 8, 10];
let res = 7;
assert_eq!(Solution::number_of_arithmetic_slices(a), res);
let a = vec![2, 2, 3, 4];
let res = 2;
assert_eq!(Solution::number_of_arithmetic_slices(a), res);
let a = vec![0, 2000000000, -294967296];
let res = 0;
assert_eq!(Solution::number_of_arithmetic_slices(a), res);
}
// Accepted solution for LeetCode #446: Arithmetic Slices II - Subsequence
function numberOfArithmeticSlices(nums: number[]): number {
const n = nums.length;
const f: Map<number, number>[] = new Array(n).fill(0).map(() => new Map());
let ans = 0;
for (let i = 0; i < n; ++i) {
for (let j = 0; j < i; ++j) {
const d = nums[i] - nums[j];
const cnt = f[j].get(d) || 0;
ans += cnt;
f[i].set(d, (f[i].get(d) || 0) + cnt + 1);
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.