Longest subsequence such that difference between adjacent is one

Pattern: LIS family

medium

Neighbours in the subsequence must differ by exactly 1. Keep best[value], the longest valid run ending with that value so far; a new x extends the better of best[x - 1] and best[x + 1].

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Return the length of the longest subsequence of arr in which every two neighbouring elements differ by exactly 1.

Think first

  • Which earlier values can come right before x?
  • Do you need their positions?
  • What replaces the O(n²) loop?

Hints

    Brute force, and why it fails

    LIS-style DP over all pairs: O(n²).

    The key insight

    Only two values can precede x, so a map lookup replaces the scan over earlier indexes.

    Dry run

    [10, 9, 4, 5, 4, 8, 6]. 10: 1, 9: 2, 4: 1, 5: 2.

    Step 1 of 2

    The plan

    best = {}
    for x: best[x] = max(best[x], 1 + max(best[x - 1], best[x + 1]))
    return max(best)
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Two lookups per value.

    Edge cases

    • One value: 1.
    • No valid pairs: 1.
    • Repeated values.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int longestSubseq(int[] arr) {
            Map<Integer, Integer> best = new HashMap<>();   // value -> the longest valid run ending with that value so far
            int answer = 0;
            for (int x : arr) {
                int len = 1 + Math.max(best.getOrDefault(x - 1, 0), best.getOrDefault(x + 1, 0));   // extend a run ending at x ± 1
                best.put(x, Math.max(best.getOrDefault(x, 0), len));
                answer = Math.max(answer, len);
            }
            return answer;
        }
    }

    C++

    class Solution {
    public:
        int longestSubseq(vector<int>& arr) {
            unordered_map<int, int> best;           // value -> the longest valid run ending with that value so far
            int answer = 0;
            for (int x : arr) {
                int a = best.count(x - 1) ? best[x - 1] : 0, b = best.count(x + 1) ? best[x + 1] : 0;
                int len = 1 + max(a, b);            // extend a run ending at x - 1 or x + 1
                best[x] = max(best[x], len);
                answer = max(answer, len);
            }
            return answer;
        }
    };

    Python

    class Solution:
        def longestSubseq(self, arr: list[int]) -> int:
            best = {}                               # value -> the longest valid run ending with that value so far
            for x in arr:
                best[x] = max(best.get(x, 0), 1 + max(best.get(x - 1, 0), best.get(x + 1, 0)))   # extend a run at x ± 1
            return max(best.values())

    Common mistakes

    • Requiring increasing order.
    • Overwriting best[x] with a smaller value.

    Similar problems