Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the longest palindrome substring as the first character.
DSA Typescript
let longest = s[1](0, 1);
Attempts:
3 left
💡 Hint
Common Mistakes
Using charAt returns a single character, not a substring.
Using slice also works but substring is preferred here.
✗ Incorrect
substring(0, 1) extracts the first character as a string, which is the initial longest palindrome.
2fill in blank
mediumComplete the code to expand around the center indices left and right.
DSA Typescript
while (left >= 0 && right < s.length && s[1](left) === s[1](right)) { left--; right++; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using substring or slice returns substrings, not single characters, causing wrong comparisons.
✗ Incorrect
charAt(index) returns the character at the given index, which is needed for comparison.
3fill in blank
hardFix the error in updating the longest palindrome substring after expanding.
DSA Typescript
if (right - left - 1 > longest.length) { longest = s[1](left + 1, right); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using charAt returns a single character, not a substring.
Using substr has different parameters and is less preferred.
✗ Incorrect
substring(left + 1, right) correctly extracts the palindrome substring after expansion.
4fill in blank
hardFill both blanks to define the helper function that expands around center indices.
DSA Typescript
function expandAroundCenter(s: string, [1]: number, [2]: number): string { let left = [1], right = [2]; while (left >= 0 && right < s.length && s.charAt(left) === s.charAt(right)) { left--; right++; } return s.substring(left + 1, right); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using start and end as parameter names is less clear here.
Mixing parameter names with variable names inside the function.
✗ Incorrect
The function parameters are left and right indices to expand around.
5fill in blank
hardFill all three blanks to complete the main function that finds the longest palindromic substring.
DSA Typescript
function longestPalindrome(s: string): string {
if (s.length < 1) return "";
let longest = s.substring(0, 1);
for (let i = 0; i < s.length; i++) {
const odd = expandAroundCenter(s, i, [1]);
const even = expandAroundCenter(s, i, [2]);
const longer = odd.length > even.length ? odd : even;
if (longer.length > longest.length) {
longest = [3];
}
}
return longest;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using i-1 or i+2 for centers causes wrong expansions.
Assigning longest to s instead of the longer palindrome substring.
✗ Incorrect
For odd length palindrome, expand around (i, i). For even length, expand around (i, i+1). Update longest with the longer palindrome.
