#730

Count Different Palindromic Subsequences

Hard
StringDynamic ProgrammingDynamic ProgrammingRecursionMemoization
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n² * 2^n)
O(n²)
Space
O(n)
O(n²)
💡

Intuition

Time O(n²)Space O(n²)

The optimal solution uses dynamic programming to count palindromic subsequences efficiently. By breaking the problem into smaller subproblems and using previously computed results, we can avoid redundant calculations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a 2D DP array where dp[i][j] represents the count of unique palindromic subsequences in the substring s[i:j].
  2. 2Step 2: Fill the DP table by considering substrings of increasing lengths.
  3. 3Step 3: For each substring, check the characters at the ends. If they are the same, include them in the count, adjusting for duplicates.
  4. 4Step 4: Return dp[0][n-1] as the result.
solution.py21 lines
1# Full working Python code
2MOD = 10**9 + 7
3
4def count_palindromic_subsequences(s):
5    n = len(s)
6    dp = [[0] * n for _ in range(n)]
7
8    for i in range(n):
9        dp[i][i] = 1  # Single character palindromes
10
11    for length in range(2, n + 1):  # Length of substring
12        for i in range(n - length + 1):
13            j = i + length - 1
14            if s[i] == s[j]:
15                dp[i][j] = dp[i + 1][j] + dp[i][j - 1] + 1
16            else:
17                dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]
18            dp[i][j] = (dp[i][j] + MOD) % MOD
19
20    return dp[0][n - 1]
21

Complexity note: The time complexity is O(n²) due to the nested loops filling the DP table, while space complexity is also O(n²) for storing the DP results.

  • 1Dynamic programming allows us to efficiently count palindromic subsequences by building on smaller solutions.
  • 2Understanding how to handle overlapping subproblems is crucial in dynamic programming.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.