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:
tis a subsequence of the strings.- The absolute difference in the alphabet order of every two adjacent letters in
tis less than or equal tok.
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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code