Similar Problems

Similar Problems not available

Longest Ideal Subsequence - Leetcode Solution

Companies:

LeetCode:  Longest Ideal Subsequence Leetcode Solution

Difficulty: Medium

Topics: string hash-table dynamic-programming  

The Longest Ideal Subsequence problem on leetcode asks us to find the length of the longest subsequence of a given array, such that the subsequence contains only distinct elements and the difference between adjacent elements is either 1 or -1.

To solve this problem, we can use dynamic programming to keep track of the longest ideal subsequence ending at each index in the array. We can initialize an array dp of the same length as the given array, and set dp[0] = 1, since the longest ideal subsequence ending at the first index is just the first element itself.

Then, for each subsequent index i in the array, we can iterate backwards from i-1 to 0 and check if any previous element j can be appended to form a longer ideal subsequence. If arr[i] - arr[j] equals 1 or -1, and dp[j] + 1 is greater than dp[i], then we can set dp[i] = dp[j] + 1, since appending j to the longest ideal subsequence ending at j gives us a longer ideal subsequence ending at i.

Finally, we can iterate through the entire dp array and find the maximum value, which will be the length of the longest ideal subsequence in the original array.

Here is the Python code to implement this solution:

def longestIdealSubsequence(arr):
    n = len(arr)
    dp = [1] * n
    
    for i in range(1, n):
        for j in range(i-1, -1, -1):
            if abs(arr[i] - arr[j]) == 1 and dp[j] + 1 > dp[i]:
                dp[i] = dp[j] + 1
                
    return max(dp)

Time Complexity: O(n^2), where n is the length of the input array. We iterate through each index in the array and perform a nested iteration for each index, so the time complexity is quadratic.

Space Complexity: O(n), where n is the length of the input array. We use an array of length n to store the longest ideal subsequence ending at each index in the array.

Longest Ideal Subsequence Solution Code

1