#1930

Unique Length-3 Palindromic Subsequences

Medium
Hash TableStringBit ManipulationPrefix SumHash MapSetDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages the properties of palindromes and uses a single pass through the string to track character occurrences. This allows us to efficiently count unique palindromic subsequences without generating all combinations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a set to store unique palindromic subsequences.
  2. 2Step 2: Use a loop to iterate through the string, keeping track of the last seen index of each character.
  3. 3Step 3: For each character, check if it has appeared before and if so, form palindromic subsequences with characters in between.
solution.py15 lines
1# Full working Python code
2
3def count_unique_palindromic_subsequences(s):
4    unique_palindromes = set()
5    last_seen = {}
6    n = len(s)
7    for i in range(n):
8        if s[i] in last_seen:
9            for j in last_seen[s[i]]:
10                unique_palindromes.add(s[j] + s[i] + s[j])
11        last_seen.setdefault(s[i], []).append(i)
12    return len(unique_palindromes)
13
14# Example usage
15print(count_unique_palindromic_subsequences('aabca'))  # Output: 3

Complexity note: The time complexity is O(n) because we only make a single pass through the string, and the operations on the set and map are average O(1). The space complexity is O(n) due to the storage of indices in the map and unique palindromes in the set.

  • 1The maximum number of unique palindromic subsequences of length 3 is limited to the distinct characters in the string.
  • 2Using a set allows us to automatically handle duplicates, ensuring we only count unique palindromic subsequences.

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