Longest palindromic subsequence (LPS) (Tabulation)

Given a string, find the length of the longest palindromic subsequence in it. For example, the length of the longest palindromic subsequence for 'bbbab' is 4 and the sequence is 'bbbb'.

Hint

Building upon understanding of Longest palindromic subsequence (LPS) (Memoization). Pay attention to the cache. Tabulation essentially reconstructs the cache.

Start with the foundation – the base cases, which are the simplest solutions. Then, layer by layer, use the results of the previous layers to calculate the solutions for the next level. This way, we systematically build up the entire solution, avoiding redundant calculations and ensuring efficiency. It is like building a pyramid.

The underlying calculation logic remains fundamentally identical to the original recursive approach, albeit executed in reverse order.

# Python implementation
def count(s):
  cache = [[1 if i == j else 0 for j in range(len(s))] for i in range(len(s))]
  
  for i in range(len(s) - 2, -1, -1):
    for j in range(i + 1, len(s)):
      if s[i] == s[j]:
        cache[i][j] = 2 + cache[i + 1][j - 1]
      else:
        cache[i][j] = max(cache[i + 1][j], cache[i][j - 1])
  
  return cache[0][len(s) - 1]

s = 'character'

print(count(s))
// Javascript implementation
function count(s) {
  let cache = Array.from(Array(s.length), () => Array(s.length).fill(0));

  for (let i = 0; i < s.length; i++) {
    cache[i][i] = 1;
  }

  for (let i = s.length - 2; i >= 0; i--) {
    for (let j = i + 1; j < s.length; j++) {
      if (s[i] === s[j]) {
        cache[i][j] = cache[i + 1][j - 1] + 2;
      } else {
        cache[i][j] = Math.max(cache[i + 1][j], cache[i][j - 1]);
      }
    }
  }

  return cache[0][s.length - 1];
}

const str = "character";

console.log(count(str));