📖 Scenario: You are working on a text analysis tool that needs to find the longest palindrome inside a given string. A palindrome is a word or phrase that reads the same backward as forward, like "madam" or "racecar".Finding the longest palindromic substring helps in various applications such as DNA sequence analysis, text processing, and error detection.
🎯 Goal: Build a JavaScript program that finds the longest palindromic substring inside a given string.You will start by setting up the input string, then add helper variables, implement the logic to find palindromes, and finally print the longest palindrome found.
📋 What You'll Learn
Create a string variable named inputString with the exact value "babad".
Create two number variables named start and maxLength initialized to 0 and 1 respectively.
Write a helper function named expandAroundCenter that takes two indices and expands outwards to check for palindromes.
Use a for loop with variable i to iterate over inputString and update start and maxLength when a longer palindrome is found.
Print the longest palindromic substring using console.log.
💡 Why This Matters
🌍 Real World
Finding palindromic substrings is useful in text analysis, DNA sequence matching, and error detection in data.
💼 Career
Understanding string manipulation and palindrome detection is important for software developers working on text processing, bioinformatics, and algorithm design.
Progress0 / 4 steps
1
Set up the input string
Create a string variable called inputString and set it to the exact value "babad".
DSA Javascript
Hint
Use const inputString = "babad"; to create the string.
2
Add helper variables for tracking palindrome
Create two number variables called start and maxLength. Initialize start to 0 and maxLength to 1.
DSA Javascript
Hint
Use let start = 0; and let maxLength = 1; to track the palindrome.
3
Implement palindrome expansion and main loop
Write a function called expandAroundCenter that takes two parameters left and right. Inside it, expand while characters at left and right are equal and within bounds. Return the length of the palindrome found. Then, use a for loop with variable i from 0 to inputString.length - 1. For each i, find lengths of odd and even palindromes by calling expandAroundCenter(i, i) and expandAroundCenter(i, i + 1). Update start and maxLength if a longer palindrome is found.
DSA Javascript
Hint
Use a helper function to expand around centers and a loop to check all centers.
4
Print the longest palindromic substring
Use console.log to print the substring of inputString starting at start with length maxLength.
DSA Javascript
Hint
Use console.log(inputString.substring(start, start + maxLength)); to print the result.
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
Step 1: Understand palindrome definition
A palindrome reads the same forwards and backwards, like 'madam' or 'racecar'.
Step 2: Identify problem goal
The problem asks to find the longest substring inside a string that is a palindrome.
Final Answer:
Find the longest substring that reads the same forwards and backwards -> Option A
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
Step 1: Understand 2D array initialization in JavaScript
Using Array.from with a mapping function creates independent inner arrays.
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.
Final Answer:
const dp = Array.from({ length: n }, () => Array(n).fill(false)); -> Option A
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
Step 1: Understand the nested loops and palindrome check
The code checks all substrings and updates the longest palindrome found.
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'.
Final Answer:
"bab" -> Option D
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
Step 1: Analyze the condition with >=
The condition uses >=, so if two palindromes have the same length, the later one overwrites the earlier.
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.
Final Answer:
Using >= causes the last palindrome to be chosen instead of the first -> Option C
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
Step 1: Understand problem and input
The string 'forgeeksskeegfor' contains a long palindrome 'geeksskeeg'.
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.
Final Answer:
Dynamic programming with 2D table; longest palindrome is 'geeksskeeg' -> Option B
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 unknownstrongwhile earning +1 Grip toward your certificate.