446. Arithmetic Slices II - Subsequence
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find the number of arithmetic subsequences in a given array nums that have a length of at least three. A subsequence is formed by deleting zero or more elements from the array while maintaining the relative order of the remaining elements. An arithmetic sequence has a constant difference between consecutive elements.
Solution
Arithmetic Slices II - Subsequence in Python
from collections import defaultdict
class Solution:
def numberOfArithmeticSlices(self, nums: list[int]) -> int:
n = len(nums)
if n < 3:
return 0
total_count = 0
# dp[i] is a dictionary where key is the difference and value is the count of
# arithmetic subsequences of length at least 2 ending at index i with that difference.
dp = [defaultdict(int) for _ in range(n)]
for i in range(1, n):
for j in range(i):
# Calculate the difference. Python integers handle arbitrary size, so no overflow.
diff = nums[i] - nums[j]
# Get the count of arithmetic subsequences ending at j with the same difference.
count_at_j = dp[j][diff]
# Any arithmetic subsequence ending at j with difference 'diff' can be extended by nums[i].
# These subsequences had length k >= 2, so the new subsequences will have length k+1 >= 3.
# We add these to our total count.
total_count += count_at_j
# Update dp[i][diff]. The number of arithmetic subsequences of length >= 2 ending at i
# with difference 'diff' is incremented by:
# 1. The subsequences extended from j (count_at_j).
# 2. The new subsequence of length 2 formed by (nums[j], nums[i]).
dp[i][diff] += count_at_j + 1
return total_count
Arithmetic Slices II - Subsequence in Java
class Solution {
public int numberOfArithmeticSlices(int[] nums) {
int n = nums.length;
if (n < 3) {
return 0;
}
long totalCount = 0;
// dp[i] is a map where key is the difference and value is the count of
// arithmetic subsequences of length at least 2 ending at index i with that difference.
@SuppressWarnings("unchecked")
Map<Long, Integer>[] dp = new HashMap[n];
for (int i = 0; i < n; i++) {
dp[i] = new HashMap<>();
}
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
// Calculate the difference. Use long to prevent overflow.
long diff = (long) nums[i] - nums[j];
// Get the count of arithmetic subsequences ending at j with the same difference.
int countAtJ = dp[j].getOrDefault(diff, 0);
// Any arithmetic subsequence ending at j with difference 'diff' can be extended by nums[i].
// These subsequences had length k >= 2, so the new subsequences will have length k+1 >= 3.
// We add these to our total count.
totalCount += countAtJ;
// Update dp[i][diff]. The number of arithmetic subsequences of length >= 2 ending at i
// with difference 'diff' is incremented by:
// 1. The subsequences extended from j (countAtJ).
// 2. The new subsequence of length 2 formed by (nums[j], nums[i]).
dp[i].put(diff, dp[i].getOrDefault(diff, 0) + countAtJ + 1);
}
}
return (int) totalCount;
}
}
Arithmetic Slices II - Subsequence in C++
class Solution {
public:
int numberOfArithmeticSlices(vector<int>& nums) {
int n = nums.size();
if (n < 3) {
return 0;
}
long long total_count = 0;
// dp[i] is a map where key is the difference and value is the count of
// arithmetic subsequences of length at least 2 ending at index i with that difference.
vector<unordered_map<long long, int>> dp(n);
for (int i = 1; i < n; ++i) {
for (int j = 0; j < i; ++j) {
// Calculate the difference. Use long long to prevent overflow.
long long diff = (long long)nums[i] - nums[j];
// Get the count of arithmetic subsequences ending at j with the same difference.
// If the key doesn't exist, 'count_at_j' will be 0.
int count_at_j = 0;
if (dp[j].count(diff)) {
count_at_j = dp[j][diff];
}
// Any arithmetic subsequence ending at j with difference 'diff' can be extended by nums[i].
// These subsequences had length k >= 2, so the new subsequences will have length k+1 >= 3.
// We add these to our total count.
total_count += count_at_j;
// Update dp[i][diff]. The number of arithmetic subsequences of length >= 2 ending at i
// with difference 'diff' is incremented by:
// 1. The subsequences extended from j (count_at_j).
// 2. The new subsequence of length 2 formed by (nums[j], nums[i]).
dp[i][diff] += count_at_j + 1;
}
}
// The problem statement guarantees the answer fits in a 32-bit integer.
return (int)total_count;
}
};
Arithmetic Slices II - Subsequence in TypeScript
function numberOfArithmeticSlices(nums: number[]): number {
const n = nums.length;
if (n < 3) {
return 0;
}
let totalCount = 0;
// dp[i] is a map where key is the difference and value is the count of
// arithmetic subsequences of length at least 2 ending at index i with that difference.
const dp: Map<number, number>[] = Array.from({ length: n }, () => new Map());
for (let i = 1; i < n; i++) {
for (let j = 0; j < i; j++) {
// Calculate the difference. JavaScript numbers are 64-bit floats,
// safe for integers up to 2^53. The difference here can be up to ~2^32,
// which is well within the safe range.
const diff = nums[i] - nums[j];
// Get the count of arithmetic subsequences ending at j with the same difference.
const countAtJ = dp[j].get(diff) || 0;
// Any arithmetic subsequence ending at j with difference 'diff' can be extended by nums[i].
// These subsequences had length k >= 2, so the new subsequences will have length k+1 >= 3.
// We add these to our total count.
totalCount += countAtJ;
// Update dp[i][diff]. The number of arithmetic subsequences of length >= 2 ending at i
// with difference 'diff' is incremented by:
// 1. The subsequences extended from j (countAtJ).
// 2. The new subsequence of length 2 formed by (nums[j], nums[i]).
const currentCountAtI = dp[i].get(diff) || 0;
dp[i].set(diff, currentCountAtI + countAtJ + 1);
}
}
return totalCount;
};
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.