Taro Logo

Longest Arithmetic Subsequence

#157 Most AskedMedium
0 views
Topics:
ArraysDynamic Programming

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.
  • A sequence seq is arithmetic if seq[i + 1] - seq[i] are all the same value (for 0 <= i < seq.length - 1).

Example 1:

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

Example 2:

Input: nums = [9,4,7,2,10]
Output: 3
Explanation:  The longest arithmetic subsequence is [4,7,10].

Example 3:

Input: nums = [20,1,15,3,10,5,8]
Output: 4
Explanation:  The longest arithmetic subsequence is [20,15,10,5].

Constraints:

  • 2 <= nums.length <= 1000
  • 0 <= nums[i] <= 500

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the minimum and maximum possible length of the input array, and what are the value ranges of the elements inside it?
  2. Can the input array contain negative numbers, zeros, and duplicate values, and how should duplicates be handled in an arithmetic subsequence?
  3. What should be returned if the input array has fewer than 2 elements?
  4. Does the order of elements in the original array need to be preserved in the subsequence, or can elements be reordered?
  5. If there are multiple valid arithmetic subsequences of the maximum length, does it matter which one we base our length count on?

Brute Force Solution

Approach

Imagine you have a row of numbers and want to find the longest sequence where the difference between every consecutive number is the exact same. The brute force approach involves trying every single possible combination of starting points and patterns to see how long you can make them go.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first number in your row.
  2. Pick a second number further down the line and figure out the exact difference between them.
  3. Keep walking down the line, using that exact same difference, to see how many more numbers you can collect that follow the pattern.
  4. Count how many numbers you managed to collect in that specific attempt.
  5. Now, go back and try a completely different starting pair of numbers with a new difference, and repeat the whole process.
  6. Exhaustively repeat this checking process for every single pair of numbers you could possibly choose as a starting point.
  7. Remember the longest chain of numbers you found during all your attempts and declare that as your final answer.

Code Implementation

Big(O) Analysis

Time Complexity
O(n³) – For each of the n elements chosen as a starting point, we must pick a second element to establish a specific difference. Then, a third inner search walks down the remaining n elements in the worst case to check if the pattern continues for that specific pair. This creates three nested dependencies across the array. The total operations scale roughly like n cubed over 6, which simplifies to O(n³) in Big O notation.
Space Complexity
O(N^2) – The auxiliary space is driven by a nested tracking structure, typically implemented as a hash map or a 2D table, where N represents the number of elements in the input array. This structure stores the length of the arithmetic subsequence for every possible pair of elements and common differences. As N increases, the number of possible index pairs and difference states grows quadratically, leading to a maximum auxiliary memory consumption proportional to N squared. Thus, the total extra memory simplifies in Big O notation to O(N^2).

Optimal Solution

Approach

Instead of testing every single combination of numbers, the optimal approach remembers the pattern history for every step we take. By building our understanding forward and keeping track of the exact difference between numbers, we can quickly find the longest matching sequence.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at pairs of numbers to figure out the exact difference or gap between them.
  2. Keep a running scorecard for every number you visit, recording how long of a sequence you have built for every possible gap size.
  3. As you move forward through the line of numbers, check what gap you are currently dealing with and look back at the previous numbers to see if that same gap has appeared before.
  4. If the gap has appeared before, take the previous sequence length associated with that gap and add one to it.
  5. If the gap has not been seen yet with a previous number, start a brand new sequence for this gap with a length of two.
  6. Continuously update your running scorecard at each stop and keep track of the highest sequence length you have found so far.
  7. Once you reach the end of the line, the highest number recorded on your scorecard will be the length of your longest arithmetic sequence.

Code Implementation

def longest_arithmetic_subsequence(sequence_numbers):
    if len(sequence_numbers) <= 2:
        return len(sequence_numbers)

    maximum_sequence_length = 1
    scorecard_map_list = [{} for _ in range(len(sequence_numbers))]

    # We evaluate all pairs to establish base sequence lengths for every potential gap.
    for current_index in range(1, len(sequence_numbers)):
        for previous_index in range(current_index):
            arithmetic_gap = sequence_numbers[current_index] - sequence_numbers[previous_index]
            
            # We extend existing sequences if the exact gap was previously observed.
            if arithmetic_gap in scorecard_map_list[previous_index]:
                sequence_length = scorecard_map_list[previous_index][arithmetic_gap] + 1
            else:
                sequence_length = 2

            scorecard_map_list[current_index][arithmetic_gap] = sequence_length
            maximum_sequence_length = max(maximum_sequence_length, sequence_length)

    # We return the global maximum to provide the length of the longest arithmetic sequence.
    return maximum_sequence_length

Big(O) Analysis

Time Complexity
O(n²) – To build the running scorecard for each number, we use two nested loops to examine every possible pair of elements in the input array of size n. For the first element we check one previous element, for the second we check two, and so on up to n-1 elements. This results in approximately n * n/2 total pair checks and scorecard updates. Dropping the constant factor gives a final Big O time complexity of O(n²).
Space Complexity
O(N^2) – The space complexity is driven by a scorecard that tracks the sequence length for every possible difference at each step, implemented as an array of hash maps or a 2D table of size N by N. As the input size N grows, the number of stored pairs of indices and differences scales quadratically to remember previous patterns. Consequently, this dynamic programming structure requires O(N^2) auxiliary memory to maintain the state for all numbers and gaps.

Edge Cases

Empty or null array input
How to Handle:
Return zero immediately as no arithmetic subsequence can be formed from fewer than one element.
Array with a single element
How to Handle:
Return one since a single element trivially forms a valid arithmetic subsequence of length one.
Array with exactly two elements
How to Handle:
Return two because any pair of numbers forms an arithmetic subsequence with a difference equal to their separation.
Array with all identical elements
How to Handle:
Return the total count of the array since the difference between consecutive identical elements is always zero.
Array with negative numbers and mixed signs
How to Handle:
Use difference calculations that properly account for signs so negative shifts do not corrupt the hash map lookups.
Extremely large array with maximum constraints
How to Handle:
Apply an O(n squared) dynamic programming approach with a hash map to avoid the O(n cubed) brute force time limit.
Large differences between elements causing integer overflow
How to Handle:
Ensure differences are computed within standard integer ranges or use language-specific wider data types if necessary.
Array in strictly descending order
How to Handle:
Track negative common differences correctly in the state table to successfully identify decreasing arithmetic subsequences.
0/257 completed