Longest Arithmetic Subsequence — LeetCode 1027 Python Solution

MediumArrayHash TableBinary SearchDynamic Programming
Problem
#1027
Reading time
2 min

The problem

Given an array nums of integers, return the length of the longest arithmetic subsequence in nums. Note that: A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

Example

Input
nums = [3,6,9,12]
Output
4
Explanation
The whole array is an arithmetic sequence with steps of length = 3.

Python solution

Python
class Solution:
    def longestArithSeqLength(self, nums: List[int]) -> int:
        n = len(nums)
        f = [[1] * 1001 for _ in range(n)]
        ans = 0
        for i in range(1, n):
            for k in range(i):
                j = nums[i] - nums[k] + 500
                f[i][j] = max(f[i][j], f[k][j] + 1)
                ans = max(ans, f[i][j])
        return ans

Complexity

MeasureComplexity
TimeO(n \times (d + n))
SpaceO(n \times d) auxiliary

Pattern: Binary Search

Halve the search space each step — over an array, or over the answer itself. LeetCode 1027. Longest Arithmetic Subsequence is filed here because LeetCode tags it Binary Search, which is the vocabulary this hub collects.

The binary search guide has the Python template for the pattern and the 254 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1027. Longest Arithmetic Subsequence?
LeetCode 1027. Longest Arithmetic Subsequence is rated Medium on LeetCode.
What is the time complexity of LeetCode 1027. Longest Arithmetic Subsequence?
The Python solution on this page runs in O(n \times (d + n)).
What is the space complexity of LeetCode 1027. Longest Arithmetic Subsequence?
The Python solution on this page uses O(n \times d) auxiliary space.
What topics does LeetCode 1027. Longest Arithmetic Subsequence cover?
LeetCode 1027. Longest Arithmetic Subsequence is tagged Array, Hash Table, Binary Search and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview