Bird
Raised Fist0
DSA Javascriptprogramming~15 mins

Longest Palindromic Substring in DSA Javascript - Deep Dive

Choose your learning style10 modes available
Overview - Longest Palindromic Substring
What is it?
The Longest Palindromic Substring problem asks us to find the longest part of a string that reads the same forwards and backwards. A palindrome is a word or phrase that is symmetrical, like 'madam' or 'racecar'. This problem helps us identify the biggest such symmetrical piece inside any given string. It is a common challenge in programming and string manipulation.
Why it matters
Finding palindromes is important in areas like DNA sequencing, text analysis, and data compression. Without this concept, we would struggle to detect symmetrical patterns that can reveal meaningful information or optimize storage. It also builds skills in string processing and dynamic programming, which are widely useful in software development.
Where it fits
Before learning this, you should understand basic strings and how to access their characters. After this, you can explore more complex string algorithms like substring search, pattern matching, and dynamic programming techniques for optimization.
Mental Model
Core Idea
The longest palindromic substring is the biggest continuous part of a string that reads the same forwards and backwards.
Think of it like...
Imagine a mirror placed in the middle of a word; the longest palindromic substring is like the largest section of the word that looks identical on both sides of the mirror.
Input: s = "babad"

Check centers:
  b | a | b | a | d
  \_/   \_/   \_/   (expand around each center)

Longest palindrome found: "bab" or "aba"

Diagram:
  Index: 0   1   2   3   4
  Char:  b - a - b - a - d
  Palindrome centers checked at each index and between indices
  Result: "bab" or "aba"
Build-Up - 7 Steps
1
FoundationUnderstanding Palindromes
šŸ¤”
Concept: Learn what a palindrome is and how to check if a string is a palindrome.
A palindrome reads the same forwards and backwards. For example, 'madam' is a palindrome because reversing it gives 'madam'. To check if a string is a palindrome, compare characters from the start and end moving towards the center.
Result
You can tell if any string is a palindrome by comparing characters symmetrically.
Understanding what makes a string a palindrome is the base for finding palindromic substrings.
2
FoundationWhat is a Substring?
šŸ¤”
Concept: Learn that a substring is a continuous part of a string.
A substring is a sequence of characters taken from a string without skipping any characters. For example, in 'hello', 'ell' is a substring but 'eol' is not because it skips characters.
Result
You can identify and extract continuous parts of a string.
Knowing substrings helps focus on continuous parts when searching for palindromes.
3
IntermediateExpand Around Center Technique
šŸ¤”Before reading on: do you think checking every possible substring is efficient or checking around centers is better? Commit to your answer.
Concept: Instead of checking all substrings, expand from each character (and between characters) to find palindromes.
For each character in the string, treat it as the middle of a palindrome and expand outwards while characters on both sides match. Also check between characters for even-length palindromes. Keep track of the longest palindrome found.
Result
You find the longest palindromic substring by expanding around centers efficiently.
Expanding around centers reduces the problem from checking all substrings to a linear number of expansions, improving efficiency.
4
IntermediateHandling Odd and Even Length Palindromes
šŸ¤”Before reading on: do you think palindromes can only be odd length? Commit to yes or no.
Concept: Palindromes can have odd or even lengths, so we must check centers at characters and between characters.
Odd length palindromes have a single center character (e.g., 'aba'). Even length palindromes have two center characters (e.g., 'abba'). We expand around both types of centers to find all palindromes.
Result
You correctly find palindromes of all lengths by checking both center types.
Recognizing both palindrome types ensures no valid palindrome is missed.
5
IntermediateImplementing the Expand Around Center in Code
šŸ¤”
Concept: Translate the center expansion logic into JavaScript code with clear steps.
Write a helper function that takes left and right indices and expands while characters match. Iterate over the string, call this helper for odd and even centers, and update the longest palindrome indices.
Result
You get a working function that returns the longest palindromic substring.
Breaking the problem into a helper function clarifies the logic and makes the code reusable.
6
AdvancedOptimizing with Dynamic Programming
šŸ¤”Before reading on: do you think dynamic programming can find palindromes faster than center expansion? Commit to yes or no.
Concept: Use a table to remember which substrings are palindromes to avoid repeated checks.
Create a 2D boolean table where table[i][j] is true if substring from i to j is palindrome. Fill the table starting with substrings of length 1 and 2, then longer substrings. Update longest palindrome when table[i][j] is true.
Result
You find the longest palindrome using a table that stores palindrome info for substrings.
Dynamic programming trades space for time by remembering palindrome checks, useful for repeated queries.
7
ExpertManacher's Algorithm for Linear Time
šŸ¤”Before reading on: do you think it's possible to find the longest palindrome in less than O(n²) time? Commit to yes or no.
Concept: Manacher's algorithm finds the longest palindromic substring in linear time by clever use of symmetry and previously computed info.
Transform the string to handle even-length palindromes uniformly. Use an array to store palindrome radii at each center. Use a center and right boundary to skip unnecessary expansions by mirroring results. Update the longest palindrome as you go.
Result
You get the longest palindromic substring in O(n) time, much faster than naive methods.
Manacher's algorithm is a powerful optimization that uses symmetry to avoid redundant checks, a rare linear solution for this problem.
Under the Hood
The expand around center method works by checking characters symmetrically around a center index or pair of indices. It stops expanding when characters differ or boundaries are reached. Dynamic programming stores palindrome states in a table to avoid repeated checks. Manacher's algorithm preprocesses the string and uses previously computed palindrome lengths and symmetry to skip redundant expansions, achieving linear time.
Why designed this way?
Naive substring checking is too slow (O(n³)). Expanding around centers reduces complexity to O(n²). Dynamic programming trades memory for speed by remembering palindrome states. Manacher's algorithm was designed to optimize further by exploiting palindrome symmetry and previously computed results, solving the problem in O(n) time, which was a significant breakthrough.
String:  a   b   a   b   a
Index:   0   1   2   3   4

Expand centers:
  (0) a
  (1) b
  (2) a
  (3) b
  (4) a

Check palindrome radius:
  For center 2: expand left=1, right=3 (b == b) -> expand left=0, right=4 (a == a)
  Palindrome: "ababa"

Manacher's array example:
  Positions: 0 1 2 3 4 5 6 7 8 9 10
  String:   # a # b # a # b # a #
  Radius:    1 2 1 4 1 6 1 4 1 2 1

Longest radius 6 at center 5 corresponds to "ababa"
Myth Busters - 4 Common Misconceptions
Quick: Is the longest palindromic substring always unique? Commit to yes or no.
Common Belief:The longest palindromic substring is always one unique substring.
Tap to reveal reality
Reality:There can be multiple longest palindromic substrings of the same maximum length.
Why it matters:Assuming uniqueness can cause bugs when returning results or testing, missing valid answers.
Quick: Does checking only odd-length palindromes find all palindromes? Commit to yes or no.
Common Belief:Checking palindromes only around single characters is enough.
Tap to reveal reality
Reality:Even-length palindromes exist and must be checked between characters.
Why it matters:Ignoring even-length palindromes misses valid palindromic substrings, leading to incorrect results.
Quick: Is Manacher's algorithm easy to implement correctly on first try? Commit to yes or no.
Common Belief:Manacher's algorithm is straightforward and simple to code.
Tap to reveal reality
Reality:Manacher's algorithm is complex and tricky to implement correctly without careful attention.
Why it matters:Underestimating its complexity leads to bugs and wasted time; understanding its logic deeply is essential.
Quick: Does dynamic programming always use less memory than expand around center? Commit to yes or no.
Common Belief:Dynamic programming uses less memory than center expansion.
Tap to reveal reality
Reality:Dynamic programming uses more memory because it stores a table of palindrome states.
Why it matters:Choosing dynamic programming without memory consideration can cause inefficiency or crashes on large inputs.
Expert Zone
1
Manacher's algorithm requires preprocessing the string with special characters to unify odd and even palindrome handling.
2
The center expansion method can be optimized by stopping early when the remaining string length is less than the current longest palindrome.
3
Dynamic programming tables can be optimized to use less space by only storing necessary previous states instead of the full table.
When NOT to use
For very large strings where memory is limited, avoid dynamic programming due to its O(n²) space. For simple or small inputs, center expansion is sufficient and easier to implement. Use Manacher's algorithm only when performance is critical and you can handle its complexity.
Production Patterns
In production, center expansion is commonly used for its simplicity and good average performance. Dynamic programming is used when multiple palindrome queries on the same string are needed. Manacher's algorithm is rare but used in performance-critical systems like DNA analysis or text editors with palindrome features.
Connections
Dynamic Programming
Builds-on
Understanding how to store and reuse results in a table for palindrome checks deepens knowledge of dynamic programming principles.
String Matching Algorithms
Related pattern
Both palindrome search and string matching involve scanning and comparing substrings efficiently, sharing optimization ideas.
Symmetry in Physics
Analogous pattern
The use of symmetry in Manacher's algorithm mirrors how symmetry simplifies problems in physics, showing cross-domain problem-solving strategies.
Common Pitfalls
#1Only checking odd-length palindromes misses even-length ones.
Wrong approach:for (let i = 0; i < s.length; i++) { expandAroundCenter(s, i, i); // only odd centers }
Correct approach:for (let i = 0; i < s.length; i++) { expandAroundCenter(s, i, i); // odd length expandAroundCenter(s, i, i + 1); // even length }
Root cause:Not realizing palindromes can have two center characters leads to incomplete checks.
#2Returning the first longest palindrome without checking all centers.
Wrong approach:let longest = ''; for (let i = 0; i < s.length; i++) { let palindrome = expandAroundCenter(s, i, i); if (palindrome.length > longest.length) { longest = palindrome; break; // stops early incorrectly } }
Correct approach:let longest = ''; for (let i = 0; i < s.length; i++) { let odd = expandAroundCenter(s, i, i); let even = expandAroundCenter(s, i, i + 1); let longer = odd.length > even.length ? odd : even; if (longer.length > longest.length) { longest = longer; } }
Root cause:Stopping early assumes first found palindrome is longest, which is false.
#3Using substring indices incorrectly causing off-by-one errors.
Wrong approach:return s.substring(start, end); // end is inclusive but substring excludes end index
Correct approach:return s.substring(start, end + 1); // include end index correctly
Root cause:Misunderstanding how substring function handles end index leads to missing last character.
Key Takeaways
A palindrome reads the same forwards and backwards, and the longest palindromic substring is the largest continuous palindrome inside a string.
Expanding around centers is an efficient way to find palindromes by checking characters symmetrically from each center.
Both odd and even length palindromes must be considered to find all possible palindromic substrings.
Dynamic programming and Manacher's algorithm offer more advanced methods to optimize palindrome search, trading space or complexity for speed.
Understanding the problem deeply helps avoid common mistakes like missing even-length palindromes or off-by-one errors in substring extraction.

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