Program to find length of longest arithmetic subsequence of a given list in Python

An arithmetic subsequence is a sequence where the difference between consecutive elements is constant. Given a list of numbers, we need to find the length of the longest arithmetic subsequence that can be formed.

For example, if we have nums = [1, 4, 7, 10, 13, 20, 16], the longest arithmetic subsequence is [1, 4, 7, 10, 13, 16] with length 6, where each consecutive difference is 3.

Algorithm Approach

We use dynamic programming with a dictionary to store subsequence lengths. For each pair of elements, we calculate their difference and track the longest subsequence ending at each position with that difference.

The algorithm steps are ?

  • Initialize a dictionary dp where dp[i, diff] represents the length of arithmetic subsequence ending at index i with common difference diff
  • For each element at position i, check all previous elements at position j
  • Calculate difference diff = arr[i] - arr[j]
  • Update dp[i, diff] = dp[j, diff] + 1
  • Track the maximum length found

Example

Let's implement the solution to find the longest arithmetic subsequence ?

from collections import defaultdict

def longest_arithmetic_subsequence(nums):
    n = len(nums)
    if n <= 1:
        return n
    
    # Dictionary to store lengths, default value is 1
    dp = defaultdict(lambda: 1)
    max_length = 0
    
    for i in range(1, n):
        for j in range(i):
            diff = nums[i] - nums[j]
            dp[i, diff] = dp[j, diff] + 1
            max_length = max(max_length, dp[i, diff])
    
    return max_length

# Test the function
nums = [1, 4, 7, 10, 13, 20, 16]
result = longest_arithmetic_subsequence(nums)
print(f"Input: {nums}")
print(f"Length of longest arithmetic subsequence: {result}")
Input: [1, 4, 7, 10, 13, 20, 16]
Length of longest arithmetic subsequence: 6

How It Works

For the example [1, 4, 7, 10, 13, 20, 16] ?

from collections import defaultdict

def trace_longest_arithmetic_subsequence(nums):
    n = len(nums)
    dp = defaultdict(lambda: 1)
    max_length = 0
    
    print("Tracing the algorithm:")
    for i in range(1, n):
        for j in range(i):
            diff = nums[i] - nums[j]
            dp[i, diff] = dp[j, diff] + 1
            max_length = max(max_length, dp[i, diff])
            print(f"i={i}, j={j}, nums[{i}]={nums[i]}, nums[{j}]={nums[j]}, diff={diff}, dp[{i},{diff}]={dp[i, diff]}")
    
    return max_length

nums = [1, 4, 7, 10, 13]  # Smaller example for clarity
result = trace_longest_arithmetic_subsequence(nums)
print(f"\nFinal result: {result}")
Tracing the algorithm:
i=1, j=0, nums[1]=4, nums[0]=1, diff=3, dp[1,3]=2
i=2, j=0, nums[2]=7, nums[0]=1, diff=6, dp[2,6]=2
i=2, j=1, nums[2]=7, nums[1]=4, diff=3, dp[2,3]=3
i=3, j=0, nums[3]=10, nums[0]=1, diff=9, dp[3,9]=2
i=3, j=1, nums[3]=10, nums[1]=4, diff=6, dp[3,6]=2
i=3, j=2, nums[3]=10, nums[2]=7, diff=3, dp[3,3]=4
i=4, j=0, nums[4]=13, nums[0]=1, diff=12, dp[4,12]=2
i=4, j=1, nums[4]=13, nums[1]=4, diff=9, dp[4,9]=2
i=4, j=2, nums[4]=13, nums[2]=7, diff=6, dp[4,6]=3
i=4, j=3, nums[4]=13, nums[3]=10, diff=3, dp[4,3]=5

Final result: 5

Time and Space Complexity

  • Time Complexity: O(n²) where n is the length of the input array
  • Space Complexity: O(n²) for storing the dp dictionary

Alternative Test Cases

# Test with different cases
test_cases = [
    [2, 4, 6, 8, 10],           # All arithmetic, diff=2
    [1, 3, 5, 7, 9, 11],        # All arithmetic, diff=2
    [1, 2, 3, 4, 7, 8, 9],      # Mixed sequences
    [5, 5, 5, 5],               # All same, diff=0
    [10, 9, 2, 5, 3, 7, 101, 18] # Complex case
]

for i, nums in enumerate(test_cases):
    result = longest_arithmetic_subsequence(nums)
    print(f"Case {i+1}: {nums}")
    print(f"Longest arithmetic subsequence length: {result}\n")
Case 1: [2, 4, 6, 8, 10]
Longest arithmetic subsequence length: 5

Case 2: [1, 3, 5, 7, 9, 11]
Longest arithmetic subsequence length: 6

Case 3: [1, 2, 3, 4, 7, 8, 9]
Longest arithmetic subsequence length: 4

Case 4: [5, 5, 5, 5]
Longest arithmetic subsequence length: 4

Case 5: [10, 9, 2, 5, 3, 7, 101, 18]
Longest arithmetic subsequence length: 4

Conclusion

This dynamic programming solution efficiently finds the longest arithmetic subsequence by tracking subsequence lengths for each difference at each position. The algorithm handles edge cases and works with any sequence of numbers, including negative differences and duplicate values.

Updated on: 2026-03-25T13:35:31+05:30

440 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements