Longest Arithmetic Subsequence solution explained

Longest Arithmetic Subsequence asks for the length of the longest subsequence, values kept in their original order but not necessarily next to each other, in which every step between consecutive values is the same. Give each index a map from step to the longest such subsequence ending there; for each earlier index j, the step d = a[i] - a[j] extends whatever j had for d by one. That is O(n²) time and O(n²) memory in the worst case.

By Published 8 min read

The problem, in plain terms

From a list of integers, keep some of them in their original order and throw the rest away. You want what remains to go up or down by the same amount at every step, like 4, 7, 10, 13 or 20, 15, 10. How long can the kept list be? Values may be skipped freely, which is the difference from the contiguous version of this problem.

Case A: [9, 4, 7, 2, 10, 13, 1]
  4 . 7 . 10 . 13   step 3
  answer: 4

Case B: [5, 5, 5]
  step 0 is allowed       answer: 3

Case C: [20, 15, 3, 10, 5, 0]
  20 15 . 10 5 0    step -5
  answer: 5
Three cases, made up for this page

Before coding, ask: can the step be negative or zero? (Both, here.) How large can values be? That decides whether a fixed-size array indexed by step is possible or a hash map is needed. And what is the answer for one or two elements? (1 and 2, since a single step is trivially constant.)

Why interviewers like it

The single-sequence DPs most candidates know keep one number per index. Here one number is not enough, because the right extension depends on the step, so the state needs a second dimension that is not an index. Interviewers want to see you discover that, choose a structure for it, and argue the transition. It also tests memory awareness: the table can hold up to n² entries, and saying so out loud is part of a complete answer.

Brute force: fix the first two values, then extend

An arithmetic subsequence of length 3 or more is fully determined by its first two values. So try every pair (i, j) with i < j as the start, set the step to a[j] - a[i], and scan right for the next value you need, taking the first one you meet. Taking the earliest match is always safe, because it leaves the most array to the right for later values. Each pair costs up to O(n) to extend, so this is O(n³) overall.

def longest_arith_cubic(a):
    n = len(a)
    if n <= 2:
        return n
    best = 2
    for i in range(n):
        for j in range(i + 1, n):
            step = a[j] - a[i]
            want = a[j] + step
            length = 2
            for k in range(j + 1, n):
                if a[k] == want:
                    length += 1
                    want += step
            best = max(best, length)
    return best
Python: every starting pair, greedy extension, O(n³)

This version recomputes the same tails over and over: once a sequence reaches index j with step d, how it continues does not depend on how it got there. That is the signal for dynamic programming.

Dynamic programming: one map per index

For each index i, keep a dictionary from step to the longest arithmetic subsequence ending at i with that step. For every earlier index j, compute d = a[i] - a[j]. If some sequence already ended at j with step d, appending a[i] makes it one longer. If none did, then a[j], a[i] is a fresh sequence of length 2. Both cases are covered by best[j].get(d, 1) + 1. Track the largest value you ever write.

def longest_arith(a):
    n = len(a)
    if n <= 2:
        return n
    best = [dict() for _ in range(n)]
    answer = 2
    for i in range(n):
        for j in range(i):
            d = a[i] - a[j]
            length = best[j].get(d, 1) + 1
            best[i][d] = length
            if length > answer:
                answer = length
    return answer
Python: list of dictionaries, O(n²) time

Overwriting best[i][d] for a later j is safe. If two earlier indexes j1 < j2 both hold the value a[i] - d, anything that ended at j1 with step d could have ended at j2 instead, so j2's entry is at least as long. Because j runs in increasing order, the last write is the best one. If that argument feels too clever under pressure, take the max of the old and new value; the cost is the same.

#include <algorithm>
#include <unordered_map>
#include <vector>

int longestArith(const std::vector<int>& a) {
    const int n = static_cast<int>(a.size());
    if (n <= 2) return n;
    std::vector<std::unordered_map<long long, int>> best(n);
    int answer = 2;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < i; ++j) {
            const long long d = static_cast<long long>(a[i]) - a[j];
            auto it = best[j].find(d);
            const int length = (it == best[j].end() ? 1 : it->second) + 1;
            best[i][d] = std::max(best[i][d], length);
            answer = std::max(answer, length);
        }
    }
    return answer;
}
C++17: vector of unordered_map, same transition

The step is stored as a 64-bit value so that subtracting two large ints cannot overflow. If you know in advance that values sit in a small range, say 0 to V, a two-dimensional array best[i][d + V] is faster than hashing, at the cost of O(n × V) memory. Ask before assuming the range.

index 1 (4):  nothing earlier with step 3
index 2 (7):  from 4  -> best[2][3] = 2
index 4 (10): from 7  -> best[4][3] = best[2][3] + 1 = 3
index 5 (13): from 10 -> best[5][3] = best[4][3] + 1 = 4
answer: 4
Case A, the entries that matter for step 3

Complexity summary

n array elements, V the value range when it is small and known
ApproachTimeExtra memoryNote
Every subsequenceO(2^n × n)O(n)Test oracle
Every starting pair, greedy extensionO(n³)O(1)Honest first answer
Map from step per indexO(n²) expectedO(n²)Expected answer
Array indexed by stepO(n²)O(n × V)Only when the value range is small
n array elements, V the value range when it is small and known. Scroll sideways on a small screen.

Edge cases to try

  • Empty, one and two elements: return 0, 1 and 2.
  • All values equal: the whole array, with step 0.
  • Strictly decreasing with an even step, like Case C: negative steps must work as dictionary keys or array offsets.
  • No three values in arithmetic order: the answer is 2.
  • Repeated values mixed with others, like [3, 3, 6, 9]: 3, 6, 9 has length 3 even though 3 appears twice.

Mistakes to avoid

  • Defaulting a missing entry to 0 instead of 1, which makes every pair count as length 1.
  • Returning 2 as the floor when the array has fewer than two values.
  • Treating it as contiguous and scanning neighbor steps only. That is the slices problem, not this one.
  • Using a fixed offset array without knowing the value range, which either wastes memory or indexes out of bounds.
  • Forgetting to mention the O(n²) memory when the interviewer asks about scale.

Follow-ups

  • The step is given. With a fixed step d, one dictionary from value to the longest sequence ending at that value suffices: O(n) time.
  • Return the subsequence. Store, with each entry, the index j it came from, then walk back from the best entry.
  • Count all arithmetic subsequences of length three or more. Store counts per (index, step) instead of lengths; the bookkeeping for the length-two pairs is the part to be careful with.
  • Very long arrays. O(n²) entries can be too many; ask whether values are bounded, which allows the array version, or whether only a few steps matter.

How to explain it out loud

Fictional example

Adding the step to the state
Candidate
If I only store the best length at each index, I lose the step, and I cannot tell whether a new value continues the sequence.
Candidate
So each index gets a map from step to the longest arithmetic run ending there.
Interviewer
How do you fill it?
Candidate
For each earlier j, the step is a[i] minus a[j]. If j already has a run with that step, I extend it by one; otherwise a[j] and a[i] start a new run of two.
Candidate
That is n squared pairs, constant expected work each with a hash map, and up to n squared entries in memory.

Arithmetic Slices is the contiguous version, solved with a single counter. Largest Divisible Subset is another chain over earlier indexes with a different link rule. Maximum Length of Repeated Subarray is also an O(n × m) pairwise table, with a reset instead of a map. Two Sum is the warm-up for looking up a needed value in a hash map.

Practicing it with Natively

The moment that matters in this problem is realizing the state needs the step, so practice saying why before you write the map. On Mac or Windows, Natively can read the prompt from a screenshot during a practice round and point you toward the per-index map, and its transcript of your mock answer shows whether you mentioned the n² memory without being asked. The AI coding interview helper page has details.

Questions people ask

How do you solve Longest Arithmetic Subsequence?

Keep a hash map for each index from step to the longest arithmetic subsequence ending there. For every pair j < i, let d = a[i] - a[j] and set the entry for i and d to j's entry for d plus one, or 2 if j had none. The largest entry is the answer.

What is the time complexity of Longest Arithmetic Subsequence?

O(n²) expected time with hash maps, and up to O(n²) memory for the entries. Trying every starting pair and extending greedily is O(n³).

Why does the DP state need the difference?

Whether a new value continues a sequence depends on that sequence's step. One length per index forgets the step, so the state has to be the pair of index and step.

Does a difference of zero count?

Yes, in the usual statement of the problem. Repeated values such as 5, 5, 5 form an arithmetic subsequence with step 0, so the answer for that array is 3.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP