#1027

Longest Arithmetic Subsequence

Medium
ArrayHash TableBinary SearchDynamic ProgrammingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal 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 track the longest arithmetic subsequence ending at each index. We leverage the differences between pairs of elements to build our solution efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a 2D array (or a hashmap) to store lengths of arithmetic subsequences with a specific difference.
  2. 2Step 2: Iterate through each pair of elements in the array to calculate the difference.
  3. 3Step 3: Update the length of the arithmetic subsequence ending at the current index based on previously computed lengths.
solution.py18 lines
1# Full working Python code
2from collections import defaultdict
3
4def longestArithSeqLength(nums):
5    n = len(nums)
6    if n < 2:
7        return n
8    dp = defaultdict(lambda: defaultdict(int))
9    max_length = 2
10
11    for j in range(n):
12        for i in range(j):
13            diff = nums[j] - nums[i]
14            dp[diff][j] = dp[diff][i] + 1
15            max_length = max(max_length, dp[diff][j] + 1)
16
17    return max_length
18

Complexity note: The time complexity remains O(n²) due to the nested loop structure, but we use additional space for the hashmap to store lengths of subsequences, leading to a space complexity of O(n).

  • 1Understanding the difference between subsequences and subsequences with specific properties is crucial.
  • 2Dynamic programming can significantly reduce the time complexity by avoiding redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.