Longest Ideal Subsequence - Problem

Given a string s consisting of lowercase letters and an integer k, you need to find the longest ideal subsequence.

A subsequence is ideal if:

  • It maintains the original order of characters from s
  • The absolute difference between any two adjacent characters in the alphabet is at most k

For example, if k = 2, then 'a' can be followed by 'a', 'b', or 'c' (since |ord('c') - ord('a')| = 2 ≤ k).

Goal: Return the length of the longest possible ideal subsequence.

Note: The alphabet is not cyclic - the distance between 'a' and 'z' is 25, not 1.

Input & Output

example_1.py — Basic Case
$ Input: s = "acfgbd", k = 2
Output: 4
💡 Note: The longest ideal subsequence is "acbd" with length 4. Adjacent differences: |c-a|=2, |b-c|=1, |d-b|=2, all ≤ k=2.
example_2.py — Small k
$ Input: s = "abcd", k = 3
Output: 4
💡 Note: The entire string "abcd" is ideal since consecutive letters have difference 1 ≤ k=3.
example_3.py — Large Gap
$ Input: s = "azbc", k = 1
Output: 2
💡 Note: Cannot include both 'a' and 'z' (difference = 25 > k=1). Best subsequences are "ab" or "bc", both length 2.

Constraints

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

Visualization

Tap to expand
🔗 Building Friendship ChainsEach person can befriend others within k=2 age yearsAChain: 1CChain: 2BChain: 3DChain: 4DP Array UpdatesProcess 'A': dp[A] = 1Process 'C': extends A → dp[C] = 2Process 'B': extends C → dp[B] = 3Process 'D': extends B → dp[D] = 4🎯 Final Answer: 4 (Chain A→C→B→D)💡 Key Insight:Each character extends the best compatible subsequence,creating optimal substructure perfect for DP!
Understanding the Visualization
1
Track Chain Endings
Keep track of the longest chain ending with each 'age group' (character)
2
Extend Compatible Chains
When a new person arrives, they can extend any compatible chain
3
Update Best Chain
Update the longest chain ending with this person's age
4
Find Global Maximum
The answer is the longest chain among all age groups
Key Takeaway
🎯 Key Insight: Each character can extend the longest compatible subsequence, creating an optimal substructure that makes dynamic programming the perfect approach with O(n×k) efficiency.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
47.0K Views
Medium-High Frequency
~18 min Avg. Time
1.9K 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