#1218

Longest Arithmetic Subsequence of Given Difference

Medium
ArrayHash TableDynamic ProgrammingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses dynamic programming with a HashMap to track the lengths of valid subsequences ending at each number. This allows us to build on previously computed results efficiently.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a HashMap to store the length of the longest subsequence ending with each number.
  2. 2Step 2: Iterate through the array, and for each number, check if the number minus the difference exists in the HashMap.
  3. 3Step 3: If it exists, update the current number's length in the HashMap based on the previous number's length plus one.
  4. 4Step 4: Keep track of the maximum length found during the iteration.
solution.py7 lines
1def longest_arith_seq(arr, difference):
2    dp = {}
3    max_length = 0
4    for num in arr:
5        dp[num] = dp.get(num - difference, 0) + 1
6        max_length = max(max_length, dp[num])
7    return max_length

Complexity note: This complexity is efficient because we only pass through the array once (O(n)), and we use a HashMap to store results, which allows for quick lookups.

  • 1Using a HashMap allows for efficient tracking of subsequence lengths.
  • 2Building on previously computed results is key in dynamic programming.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.