Bird
Raised Fist0
DSA Javascriptprogramming

Longest Palindromic Substring in DSA Javascript

Choose your learning style10 modes available
Mental Model
Find the longest part of a string that reads the same forwards and backwards by expanding around each center.
Analogy: Imagine looking for a mirror in the middle of a word and checking if the letters on both sides match like reflections.
s = "b a n a n a"
indexes: 0 1 2 3 4 5
Check centers like:
  a
 b a n a n a
    ↑
Expand left and right to find palindrome
Dry Run Walkthrough
Input: string: "banana"
Goal: Find the longest substring that reads the same forwards and backwards
Step 1: Start with center at index 0 (character 'b'), expand around it
"b" -> palindrome length 1
Why: Every single character is a palindrome of length 1
Step 2: Center at index 1 (character 'a'), expand around it
"a" -> palindrome length 1
Why: Check odd length palindrome centered at 'a'
Step 3: Center between index 1 and 2 (between 'a' and 'n'), expand around it
palindrome length 0
Why: Check even length palindrome between 'a' and 'n'
Step 4: Center at index 2 (character 'n'), expand around it
"ana" -> palindrome length 3
Why: Check odd length palindrome centered at 'n'
Step 5: Center between index 2 and 3 (between 'n' and 'a'), expand around it
palindrome length 0
Why: Check even length palindrome between 'n' and 'a'
Step 6: Center at index 3 (character 'a'), expand around it
"anana" -> palindrome length 5
Why: Expand left and right to find palindrome 'anana'
Step 7: Center between index 3 and 4 (between 'a' and 'n'), expand around it
palindrome length 0
Why: Check even length palindrome between 'a' and 'n'
Step 8: Center at index 4 (character 'n'), expand around it
"ana" -> palindrome length 3
Why: Expand left and right to find palindrome 'ana'
Step 9: Center between index 4 and 5 (between 'n' and 'a'), expand around it
palindrome length 0
Why: Check even length palindrome between 'n' and 'a'
Step 10: Center at index 5 (character 'a'), expand around it
"a" -> palindrome length 1
Why: Check odd length palindrome centered at last character
Result:
"anana" is the longest palindromic substring
Annotated Code
DSA Javascript
class Solution {
  longestPalindrome(s) {
    if (s.length === 0) return "";
    let start = 0, end = 0;

    const expandAroundCenter = (left, right) => {
      while (left >= 0 && right < s.length && s[left] === s[right]) {
        left--;
        right++;
      }
      return right - left - 1;
    };

    for (let i = 0; i < s.length; i++) {
      const len1 = expandAroundCenter(i, i); // odd length palindrome
      const len2 = expandAroundCenter(i, i + 1); // even length palindrome
      const len = Math.max(len1, len2);
      if (len > end - start) {
        start = i - Math.floor((len - 1) / 2);
        end = i + Math.floor(len / 2);
      }
    }

    return s.substring(start, end + 1);
  }
}

const sol = new Solution();
const input = "banana";
console.log(sol.longestPalindrome(input));
while (left >= 0 && right < s.length && s[left] === s[right]) { left--; right++; }
expand left and right pointers while characters match to find palindrome length
const len1 = expandAroundCenter(i, i);
check odd length palindrome centered at i
const len2 = expandAroundCenter(i, i + 1);
check even length palindrome centered between i and i+1
if (len > end - start) { start = i - Math.floor((len - 1) / 2); end = i + Math.floor(len / 2); }
update start and end indices if a longer palindrome is found
OutputSuccess
anana
Complexity Analysis
Time: O(n^2) because for each character we expand around centers which can take up to n steps
Space: O(1) because we only use a few variables to track indices and lengths
vs Alternative: Better than checking all substrings (O(n^3)) because we avoid redundant checks by expanding around centers
Edge Cases
empty string
returns empty string immediately
DSA Javascript
if (s.length === 0) return "";
string with all identical characters
returns the entire string as palindrome
DSA Javascript
while (left >= 0 && right < s.length && s[left] === s[right]) { left--; right++; }
string with no palindrome longer than 1
returns any single character
DSA Javascript
const len1 = expandAroundCenter(i, i);
When to Use This Pattern
When asked to find the longest substring that reads the same forwards and backwards, use the expand around center pattern because it efficiently checks palindromes without checking all substrings.
Common Mistakes
Mistake: Only checking odd length palindromes and missing even length ones
Fix: Check both odd and even length palindromes by expanding around i and between i and i+1
Mistake: Not updating start and end indices correctly after finding a longer palindrome
Fix: Calculate start and end using the palindrome length and center index carefully
Summary
Finds the longest substring that reads the same forwards and backwards by expanding around centers.
Use when you need to find the longest palindromic substring efficiently without checking all substrings.
The key insight is to expand around each character (and between characters) to find palindromes in O(n^2) time.

Practice

(1/5)
1. What is the main goal of the Longest Palindromic Substring problem?
easy
A. Find the longest substring that reads the same forwards and backwards
B. Find the longest substring with all unique characters
C. Find the longest substring with increasing characters
D. Find the longest substring that contains only vowels

Solution

  1. Step 1: Understand palindrome definition

    A palindrome reads the same forwards and backwards, like 'madam' or 'racecar'.
  2. Step 2: Identify problem goal

    The problem asks to find the longest substring inside a string that is a palindrome.
  3. Final Answer:

    Find the longest substring that reads the same forwards and backwards -> Option A
  4. Quick Check:

    Longest Palindromic Substring = Find palindrome substring [OK]
Hint: Look for substrings that mirror around a center [OK]
Common Mistakes:
  • Confusing palindrome with unique characters
  • Thinking about subsequences instead of substrings
  • Ignoring the order of characters
2. Which of the following JavaScript code snippets correctly initializes a 2D array dp for dynamic programming in the Longest Palindromic Substring problem?
easy
A. const dp = Array.from({ length: n }, () => Array(n).fill(false));
B. const dp = Array(n).fill(Array(n).fill(false));
C. const dp = new Array(n).fill(new Array(n).fill(false));
D. const dp = Array(n).map(Array(n).fill(false));

Solution

  1. Step 1: Understand 2D array initialization in JavaScript

    Using Array.from with a mapping function creates independent inner arrays.
  2. Step 2: Analyze each option

    B and C fill with the same inner array reference, causing bugs. D uses map incorrectly by passing an array instead of a function, which won't work. A correctly creates independent arrays.
  3. Final Answer:

    const dp = Array.from({ length: n }, () => Array(n).fill(false)); -> Option A
  4. Quick Check:

    Correct 2D array init = const dp = Array.from({ length: n }, () => Array(n).fill(false)); [OK]
Hint: Use Array.from with arrow function for independent inner arrays [OK]
Common Mistakes:
  • Using fill with object references causing shared inner arrays
  • Using map on uninitialized arrays
  • Not initializing inner arrays separately
3. What will be the output of the following JavaScript code snippet?
function longestPalindrome(s) {
  let maxLen = 1, start = 0;
  for (let i = 0; i < s.length; i++) {
    for (let j = i; j < s.length; j++) {
      let substr = s.slice(i, j + 1);
      if (substr === substr.split('').reverse().join('') && substr.length > maxLen) {
        maxLen = substr.length;
        start = i;
      }
    }
  }
  return s.slice(start, start + maxLen);
}
console.log(longestPalindrome('babad'));
medium
A. "aba"
B. "babad"
C. "bad"
D. "bab"

Solution

  1. Step 1: Understand the nested loops and palindrome check

    The code checks all substrings and updates the longest palindrome found.
  2. Step 2: Trace substrings in 'babad'

    Palindromes found include 'bab' and 'aba', both length 3. The code updates maxLen and start when it finds 'aba' last (i=1,j=3), because the condition uses >, so it updates only if strictly longer. 'bab' is found first but 'aba' is found later and has the same length, so it is not updated. Actually, the code updates only if substr.length > maxLen, so the first palindrome of length 3 is 'bab' (i=0,j=2), maxLen becomes 3. Then 'aba' (i=1,j=3) is also length 3, so substr.length > maxLen is false (3 > 3 is false), so maxLen and start are not updated. Therefore, the returned palindrome is 'bab'.
  3. Final Answer:

    "bab" -> Option D
  4. Quick Check:

    First longest palindrome found = "bab" [OK]
Hint: Check all substrings; first longest palindrome returned [OK]
Common Mistakes:
  • Assuming 'aba' is returned instead of 'bab'
  • Confusing substring with subsequence
  • Ignoring order of substring checks
4. The following code attempts to find the longest palindromic substring but has a bug. What is the bug?
function longestPalindrome(s) {
  let maxLen = 1, start = 0;
  for (let i = 0; i < s.length; i++) {
    for (let j = i; j < s.length; j++) {
      let substr = s.slice(i, j + 1);
      if (substr === substr.split('').reverse().join('') && substr.length >= maxLen) {
        maxLen = substr.length;
        start = i;
      }
    }
  }
  return s.slice(start, start + maxLen);
}
console.log(longestPalindrome('cbbd'));
medium
A. The reverse method does not work on strings
B. The slice method is used incorrectly
C. Using >= causes the last palindrome to be chosen instead of the first
D. The loop ranges are off by one

Solution

  1. Step 1: Analyze the condition with >=

    The condition uses >=, so if two palindromes have the same length, the later one overwrites the earlier.
  2. Step 2: Understand effect on output

    For input 'cbbd', palindromes 'bb' and 'b' exist. Using >= picks the last palindrome of max length, which may not be desired.
  3. Final Answer:

    Using >= causes the last palindrome to be chosen instead of the first -> Option C
  4. Quick Check:

    Condition >= picks last palindrome [OK]
Hint: Use > to pick first longest palindrome found [OK]
Common Mistakes:
  • Thinking slice is incorrect
  • Believing reverse doesn't work on strings
  • Ignoring >= vs > difference
5. Given the string s = 'forgeeksskeegfor', which approach below efficiently finds the longest palindromic substring and what is that substring?
hard
A. Expand around center approach; longest palindrome is 'eeksskee'
B. Dynamic programming with 2D table; longest palindrome is 'geeksskeeg'
C. Sorting characters and checking; longest palindrome is 'ss'
D. Brute force checking all substrings; longest palindrome is 'forgeeksskeegfor'

Solution

  1. Step 1: Understand problem and input

    The string 'forgeeksskeegfor' contains a long palindrome 'geeksskeeg'.
  2. Step 2: Evaluate approaches

    Brute force checking all substrings is inefficient and won't find the full string palindrome. Sorting characters loses order, so 'ss' is incorrect. Dynamic programming with 2D table finds 'geeksskeeg' correctly, unlike other options.
  3. Final Answer:

    Dynamic programming with 2D table; longest palindrome is 'geeksskeeg' -> Option B
  4. Quick Check:

    DP approach finds 'geeksskeeg' efficiently [OK]
Hint: Use DP table to track palindromes efficiently [OK]
Common Mistakes:
  • Assuming whole string is palindrome
  • Using sorting which breaks character order
  • Confusing expand around center with brute force
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard