Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
How Many Palindromic Substrings Are There is String S?

I am trying to solve the problem "How many palindromic substrings can you find in string s" in the same way that you might solve the problem "Find the Longest Palindromic Substring in String s". That is, I would like to use the Longest Palindromic Subsequence Pattern to solve this problem. I know you can expand from the centre of each character and check if it is a palindrome, but I would like to see how to solve this problem in using the mentioned pattern.

Here is the working code to compute the longest palindromic substring.

var longestPalindrome = function(s) {
  
  const fn = (start, end) => {
    
    if (start > end) return "";
    if (start === end) return s[start];
    
    if (s[start] === s[end]) {
      const innerSearchSpaceSize = end - start - 1;
      const lonestPalindromeFromInnerSearchSpace = fn(start + 1, end - 1);
      if (innerSearchSpaceSize === lonestPalindromeFromInnerSearchSpace.length)
        return s[start] + lonestPalindromeFromInnerSearchSpace + s[end];
    }

    const longestPalindromeFromRightSide = fn(start + 1, end);
    const longestPalindromeFromLeftSide = fn(start, end - 1);

    return longestPalindromeFromRightSide.length >
      longestPalindromeFromLeftSide.length
      ? longestPalindromeFromRightSide
      : longestPalindromeFromLeftSide;
  };

  return fn(0, s.length - 1);
};

Here is my attempt at solving the count of all palindromic substrings.

var countPalindromes = function (s) {
  
  const fn = (start, end) => {
    if (start > end) return 0;
    if (start === end) return 1;

    if (s[start] === s[end]) return fn(start + 1, end - 1) + 3;

    return fn(start + 1, end) + fn(start, end - 1) - fn(start + 1, end - 1);
  };

  return fn(0, s.length - 1);
};

Note: I know I need to use memoization on these problems. I am omitting that for now and just focusing on the recursion.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!