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 SubsequenceFind longest subsequence with adjacent character differences ≤ kInput String:a c f g i kk = 2 (max allowed difference)acik|c-a|=2✓valid path|k-i|=2✓Valid Subsequence: "acik"Output: 4All adjacent pairs have difference ≤ 2
Understanding the Visualization
1
Input
String s and compatibility distance k
2
Process
Find subsequence where adjacent chars differ by ≤ k
3
Output
Length of longest valid subsequence
Key Takeaway
🎯 Key Insight: Use DP to track the longest subsequence ending at each character, extending only from compatible previous characters.
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