Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the longest palindromic substring length.
DSA C#
public int LongestPalindromeLength(string s) {
int maxLength = 1;
for (int i = 0; i < s.Length; i++) {
int len1 = ExpandAroundCenter(s, i, i);
int len2 = ExpandAroundCenter(s, i, i + [1]);
maxLength = Math.Max(maxLength, Math.Max(len1, len2));
}
return maxLength;
}
private int ExpandAroundCenter(string s, int left, int right) {
while (left >= 0 && right < s.Length && s[left] == s[right]) {
left--;
right++;
}
return right - left - 1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 instead of 1 causes checking the same center twice.
Using 2 or -1 causes index errors or wrong palindrome checks.
✗ Incorrect
The second center for even-length palindromes starts at i and i+1, so the offset is 1.
2fill in blank
mediumComplete the code to update the start index of the longest palindrome found.
DSA C#
if (len > maxLength) { maxLength = len; start = i - ([1] - 1) / 2; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using len instead of len - 1 causes off-by-one errors.
Using len + 1 or len * 2 causes incorrect start positions.
✗ Incorrect
To find the start index, subtract half of the palindrome length minus one from the center index.
3fill in blank
hardFix the error in the palindrome expansion loop condition.
DSA C#
while (left >= 0 && right < s.Length && s[[1]] == s[right]) { left--; right++; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using right for both indices causes comparing the same character.
Using left + 1 or right - 1 causes index errors.
✗ Incorrect
We compare characters at left and right indices, so s[left] must be compared to s[right].
4fill in blank
hardFill both blanks to correctly extract the longest palindromic substring.
DSA C#
return s.Substring([1], [2]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using i instead of start causes wrong substring extraction.
Using len instead of maxLength causes inconsistent length.
✗ Incorrect
Substring needs the start index and the length of the palindrome.
5fill in blank
hardFill all three blanks to complete the palindrome length calculation and update logic.
DSA C#
int len1 = ExpandAroundCenter(s, i, i); int len2 = ExpandAroundCenter(s, i, i + [1]); int len = Math.Max(len1, len2); if (len > maxLength) { maxLength = len; start = i - (len - 1) / [2]; } return s.Substring(start, [3]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 instead of 1 for the second center causes wrong palindrome checks.
Using len instead of maxLength for substring length causes errors.
✗ Incorrect
The second center offset is 1; dividing by 2 finds half length; substring length is maxLength.
