Back to course home
0% completed
Vote For New Content
Two pointers - Time O(N**2) and Space O(1)
singhursefamily
Oct 31, 2025
The two dynamic programming solutions have time and space complexity both of O(N^2).
I found a solution that also has a time complexity of O(N^2) but reduces the space complexity to O(1). It uses a two pointer approach. The code in in Javascript.
findLPSLength(str) { // two pointers, one on each end of `str` let left = 0; let right = str.length - 1; // size of the palindrome. this is the function output. let size = 0; while (left < right) { const target = str[left]; let r; for (r = right; r > left; r -= 1) { const consider = str[r]; if (target === consider) { size += 2; break; } } // move right pointer only if a match was found. // (r will be greater than left because of the `break`) if (r > left) { right = r - 1; } // increment left whether there was a match or not left += 1; } // if the loop ended with left and right on the same char // we can add that char to the palindrome if (left === right) { size += 1; } return size; }
0
0
Comments
Comments