The fastest method for finding the longest palindrome subsequence within a given string

I've been working on creating a function that can identify the longest palindrome subsequence within a given string. After experimenting with dynamic programming, I came up with the code snippet below:

function findLongestPalindrome(str) {
  let length = str.length;
  let memoization = Array(length);
  for (let i = 0; i < length; i++) {
    memoization[i] = Array(length);
    memoization[i][i] = 1;
  }
  for (let cl = 2; cl <= length; cl++) {
    for (let i = 0; i < length - cl + 1; i++) {
      let j = i + cl - 1;
      if (str[i] === str[j] && cl === 2)
        memoization[i][j] = 2;
      else if (str[i] === str[j])
        memoization[i][j] = memoization[i + 1][j - 1] + 2;
      else
        memoization[i][j] = Math.max(memoization[i][j - 1], memoization[i + 1][j]);
    }
  }
  return memoization[0][length - 1];
}

Despite my efforts, this implementation isn't consistently efficient across all test cases and the Time and Space Complexity needs to be optimized further. I've been stuck on this problem for some time now and can't seem to pinpoint the issue. If anyone could provide insight on what might be going wrong and suggest potential solutions, it would be greatly appreciated.

Answer №1

According to my analysis, Dynamic Programming may not be the best approach for tackling this particular problem. This is because it does not break down recursively. For instance, when searching for the longest palindrome in a string, you don't necessarily need to consider all second-largest palindromes. Instead, you can simply examine each position and determine if it marks the center of a palindrome longer than any previously encountered. A more efficient way to solve this problem would involve using a greedy algorithm:

const pals = "asd1234321fghjkl1234567887654321qwertzu1234321"

function palindromeAtPos(str, pos, checkEven = false){
  let ix = 0
  const off = checkEven ? 2 : 1
  while(pos-ix-1 >= 0 && pos+ix+1+off < str.length && str[pos-ix-1] === str[pos+ix+off]){
    ix++
  }
  return ix === 0 ? str[pos] : str.substring(pos-ix, pos+ix+off)
}

function longestPalindrome(str){
  let longest = ''
  for(let i = 1; i < str.length; i++){
    const odd = palindromeAtPos(str, i)
    longest = odd.length > longest.length ? odd : longest
    const even = palindromeAtPos(str, i, true)
    longest = even.length > longest.length ? even : longest
  }
  return longest
}

console.log(longestPalindrome(pals))

Although the complexity of this algorithm is quadratic on paper (especially with strings like aaaaaaaaaa), in practice, it tends to exhibit almost linear behavior for most strings.

Answer №2

/*
*   x => integer
*   return [] of integers which are multiples of 2
*/
function getMultiplesOfTwo(x) {
   const arr = []
   for (let i = 1; i <= x; i++) {
      if (i % 2 === 0) {
         arr.push(i)
      }
   }
   return arr
}

const num1 = 10
const num2 = 20
const num3 = 30

console.log(getMultiplesOfTwo(num1))
console.log(getMultiplesOfTwo(num2))
console.log(getMultiplesOfTwo(num3))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customize the default directory for local node modules installation in node.js using npm

If I prefer not to have my local (per project) packages installed in the node_modules directory, but rather in a directory named sources/node_modules, is there a way to override this like you can with bower? In bower, you specify the location using a .bow ...

Using identical content in various template slots

Is it possible in vuejs to assign the same content to multiple slots without repeating it? For example: <base-layout> <template slot="option"> <span :class="'flag-icon-' props.option.toLowerCase()" />{{ countriesByCode ...

Creating a Build System for JavaScript in Sublime Text

While working on developing an application using node.js, I decided to create a JavaScript build system in Sublime Text 3 on my Ubuntu OS. I made a new build system file named nodey.sublime-build with the following contents: { "cmd": ["node","$file"," ...

The breeze is puzzled by the altered being, unable to identify it

I am currently working on a breeze implementation that involves displaying properties from a location object on the UI. However, when I make changes to some properties and attempt to save them, breeze does not recognize the entity as being changed. Here is ...

What is the best way to customize the functionality of the Done (node-dialog-ok) button in node-red when it is

I have created a custom node and I want to trigger some specific actions when the 'Done' button (with id: node-dialog-ok) in the editor-tray-toolbar is clicked, instead of its default functionality. Is it possible to override the onclick event o ...

Update the variable using Ajax after the content has loaded

I am struggling with the following code snippet: <?php $num=12; ?> <html> <head></head> <body> <div id="test"></div> <script type="text/javascript"> function fetchContent() { var ...

developing a dynamic map with javascript

In the image provided, my concept is for it to initially be without a green tint. However, when the user hovers over specific areas, they would turn green and become clickable links. There are multiple areas in the image, with this being just one example. ...

What is the reason behind jshint issuing an alert specifically for the lastSelectedRow being

Upon pasting the code below into jshint.com, an error is generated: Read only in reference to line: lastSelectedRow = 1; I am curious as to why this error occurs and how it can be remedied. Interestingly, jslint does not return this error. /*global la ...

Utilize a jQuery selector to target the initial element of every alphabet character

I'm seeking some assistance with jQuery selectors and have a specific scenario that I need help with. Here is the HTML structure I am working with: <ul> <li class="ln-a"></li> <li class="ln-b"></li> <li cl ...

Is it possible to modify the labels on CKEditor's toolbar elements?

Initializing CKEditor in the following manner: function init() { $( ".ckeditor" ).ckeditor( { format_tags: 'h3;p', toolbar: [ [ "Source", "-", "Bold", "Italic" ], [ "Link", "Unlink" ], [ "Blockquote", "F ...

Exploring the Relationship Between jQuery and JSON through Iterating Over JSON Arrays

There is an array stored in a database: a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";} To manipulate this array, I first unserialize it using PHP and then encode it with JSON. The code snippet is as follows: $unwp = unserialize(&apos ...

Utilizing checkboxes to toggle the visibility of a div element with varying headings

By toggling a checkbox, I aim to show or hide the same div with a different heading. $('#cbxShowHide').click(function() { this.checked ? $('#block').show(1000) : $('#block').hide(1000); }); #block { display: none; bac ...

"Implementation of Google+ button causing the appearance of a horizontal scrollbar

Adding Facebook and Twitter sharing buttons was easy, but now I'm having trouble with Google+. No matter where I place the code on my page (using a Bootstrap grid), it always adds 2-3 pixels on the right side, creating a horizontal scrollbar: <div ...

Using the Flow type checker with React library results in complications

I'm fairly new to JavaScript and React, so I appreciate your patience! I've recently started a project using create-react-app with React version 16.12.0. I installed a library that seems to be utilizing Flow. When attempting to use this library ...

What is the best way to manage a download link that necessitates an Authorization token when using Angular?

I'm currently working with a REST API in combination with Angular. The issue I'm facing is related to post objects that include file attachments. Every time a user wants to download a file attachment, they must make a call to /get/file/{id}, but ...

Conflicting Angular components: Sorting tables and dragging/dropping table rows

In the current project I'm working on, I've integrated both angular table-sort and angular drag-drop. However, I ran into an issue where dragging a row and attempting to drop it onto another row causes the table sort to forcefully rearrange the r ...

To activate a function, simply click anywhere on the body: instruction

One of my latest projects involved creating a directive that allows users to click on a word and edit it in a text box. Once edited, clicking anywhere on the body should return the word back to its updated form. html <div markdown>bineesh</div& ...

"Troubleshooting 3D Models not appearing correctly in Mapbox when using Three.js

My issue lies in the inability to load any .gltf file, only a standard one. For further details, please continue reading. The map on my application showcases a 3D model indicated by the red arrow: https://i.sstatic.net/3Ce09.png The model is a GLTF file ...

Can you provide the Angular JS alternative for executing a POST request similar to this Curl command?

Trying to translate a Curl command into Angular JS code has been a challenge for me as a newcomer to AngularJS. This specific instance involves a mobile app built on the ionic framework, which utilizes Angular JS. The original curl command looks like this ...

Misunderstandings between HTML and CSS

Can someone please clarify how the functionality of the active-slide class? Code: <div class="slider"> <div class="slide active-slide">..</div> <div class = "slide slide-feature">..</div> <div class = "slide">..</di ...