874781. Longest subsequence with difference

Medium

Here is a detailed Markdown blog post for the problem "Longest subsequence with difference":

Longest Subsequence with Difference

Summary

Given an array of integers, find the longest subsequence where every pair of adjacent elements in the subsequence has a certain difference. For example, if the given array is [1, 3, 5, 7, 9] and the required difference is 2, then the longest subsequence would be [1, 3, 5, 7]. This problem requires an understanding of arrays, hash, and algorithms.

Detailed Explanation

The approach to solve this problem involves iterating through the array and using a hashmap to store the differences between consecutive elements. For each element, we check if the difference exists in the hashmap. If it does, then we update the maximum length of the subsequence with the same difference. We also update the hashmap with the current difference.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty hashmap diffMap to store the differences and their counts.
  2. Iterate through the array from left to right.
  3. For each element, calculate the difference between the current element and the previous one (or 0 if it's the first element).
  4. Check if the difference exists in the hashmap. If it does, update the maximum length of the subsequence with the same difference.
  5. Update the hashmap with the current difference.
  6. Repeat steps 3-5 until the end of the array is reached.
  7. Return the maximum length of the subsequence.

Time Complexity: O(n), where n is the size of the input array. Space Complexity: O(m), where m is the number of unique differences in the array.

Optimized Solutions

Java

View on GeeksforGeeks
public int longestSubsequence(int[] arr, int diff) {
    Map<Integer, Integer> diffMap = new HashMap<>();
    int maxLen = 0;
    
    for (int i = 0; i < arr.length; i++) {
        int curDiff = arr[i] - (i == 0 ? 0 : arr[i-1]);
        if (!diffMap.containsKey(curDiff)) {
            diffMap.put(curDiff, 1);
        } else {
            maxLen = Math.max(maxLen, diffMap.get(curDiff) + 1);
            diffMap.put(curDiff, diffMap.get(curDiff) + 1);
        }
    }
    
    return maxLen;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.