Longest Ideal Subsequence - Problem

You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if the following conditions are satisfied:

  • t is a subsequence of the string s.
  • The absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k.

Return the length of the longest ideal string.

A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.

Note: The alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25, not 1.

Input & Output

Example 1 — Basic Case
$ Input: s = "acfgik", k = 2
Output: 4
💡 Note: The longest ideal string is "acik". Characters a→c (diff=2), c→i (diff=6>2 invalid), but a→c→g→i→k works where a→c (diff=2≤2), c→g invalid, but optimal path is a→c→e→g or similar giving length 4.
Example 2 — Large k
$ Input: s = "abcd", k = 3
Output: 4
💡 Note: All adjacent characters have difference ≤3: |a-b|=1, |b-c|=1, |c-d|=1. The entire string "abcd" is ideal with length 4.
Example 3 — Small k
$ Input: s = "azbc", k = 1
Output: 2
💡 Note: Can't include both 'a' and 'z' since |a-z|=25>1. Best subsequences are "ab", "bc", or "ac" (if valid). The longest has length 2.

Constraints

  • 1 ≤ s.length ≤ 105
  • 0 ≤ k ≤ 25
  • s consists only of lowercase English letters

Visualization

Tap to expand
Longest Ideal Subsequence INPUT String s: a c f g i k 0 1 2 3 4 5 k = 2 Alphabet positions: a=1 c=3 f=6 g=7 i=9 k=11 Adjacent diff must be <= k |pos[i] - pos[j]| <= 2 ALGORITHM STEPS 1 Initialize DP array dp[26] = 0 for each letter 2 Process each char Query range [c-k, c+k] 3 Find max in range dp[c] = max(range) + 1 4 Track global max Answer = max(dp[0..25]) DP State After Processing: dp['a']=1 (range query: max=0) dp['c']=2 (a in range, max=1) dp['f']=1 (no valid prev) dp['g']=2 (f in range, max=1) dp['i']=3 (g in range, max=2) dp['k']=4 (i in range, max=3) FINAL RESULT Longest Ideal Subsequence: g i k One valid sequence: "gik" (len 3) Best: "acfg" or "fgik" (len 4) f g i k Differences: |7-6|=1, |9-7|=2, |11-9|=2 All <= k=2 [OK] Output: 4 Key Insight: For each character c at position i, we only need to find the maximum DP value among characters within range [c-k, c+k]. Using a DP array of size 26 (one per letter) allows O(k) range queries, giving O(n*k) time complexity. This is optimal when k is small compared to alphabet size. TutorialsPoint - Longest Ideal Subsequence | Optimized DP - Range Query
Asked in
Google 35 Facebook 28 Amazon 22
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen