We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Longest Ideal Subsequence

Difficulty: Medium


Problem Description

You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if it is a subsequence of the string s and 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.


Key Insights

  • An ideal string must be a subsequence of the original string s.
  • The difference in the alphabet order of adjacent characters must be no greater than k.
  • We can utilize dynamic programming to keep track of the longest ideal subsequence for each character in the alphabet.

Space and Time Complexity

Time Complexity: O(n + 26) where n is the length of the string s (26 is for the fixed number of lowercase letters).
Space Complexity: O(1) since we are using a fixed-size array of 26 for counting.


Solution

We can solve this problem using a dynamic programming approach. We maintain an array dp of size 26, where dp[i] will store the length of the longest ideal subsequence ending with the character corresponding to i (0 for 'a', 1 for 'b', ..., 25 for 'z').

For each character in the string s, we check its position in the alphabet and update our dp array based on the allowed range of characters determined by k. Specifically, for each character s[j], we can look at characters from s[j]-k to s[j]+k and calculate the maximum ideal subsequence length that can end with s[j].


Code Solutions

def longestIdealString(s: str, k: int) -> int:
    dp = [0] * 26  # dp[i] will hold the length of the longest ideal subsequence ending with character i
    for char in s:
        index = ord(char) - ord('a')
        current_max = 0
        # Check the range of characters that can be adjacent
        for j in range(max(0, index - k), min(25, index + k) + 1):
            current_max = max(current_max, dp[j])
        dp[index] = current_max + 1  # Update dp for the current character
    return max(dp)  # The result is the maximum value in dp
← Back to All Questions