#2370
Longest Ideal Subsequence
MediumHash TableStringDynamic ProgrammingDynamic ProgrammingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can use dynamic programming to build the solution incrementally. By maintaining an array that tracks the longest ideal subsequence ending at each character, we can efficiently compute the result.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a dp array where dp[i] represents the length of the longest ideal subsequence ending with character s[i].
- 2Step 2: Iterate through each character in the string s.
- 3Step 3: For each character, check previous characters to see if they can be part of an ideal subsequence (i.e., their difference is <= k).
- 4Step 4: Update dp[i] based on the maximum length found from valid previous characters.
- 5Step 5: The result will be the maximum value in the dp array.
solution.py12 lines
1# Full working Python code
2def longestIdealSubsequence(s, k):
3 dp = [0] * 26
4 max_length = 0
5 for char in s:
6 index = ord(char) - ord('a')
7 current_length = 1
8 for j in range(max(0, index - k), min(25, index + k) + 1):
9 current_length = max(current_length, dp[j] + 1)
10 dp[index] = max(dp[index], current_length)
11 max_length = max(max_length, dp[index])
12 return max_lengthℹ
Complexity note: The time complexity is O(n) because we iterate through the string once and check a fixed range of characters (at most 26) for each character in the string.
- 1The problem can be approached using dynamic programming to build solutions incrementally.
- 2Understanding the relationship between characters and their indices in the alphabet is crucial for checking the ideal conditions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.