Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if a substring is a palindrome.
DSA Java
private boolean isPalindrome(String s, int left, int right) {
while (left < right) {
if (s.charAt(left) != s.charAt([1])) {
return false;
}
left++;
right--;
}
return true;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using left + 1 or right - 1 instead of right causes wrong character comparison.
Comparing s.charAt(left) with s.charAt(left) always returns true.
✗ Incorrect
We compare characters at positions 'left' and 'right' to check palindrome. So s.charAt(right) is correct.
2fill in blank
mediumComplete the code to add a substring to the current partition list.
DSA Java
List<String> current = new ArrayList<>(); String s = "aab"; int start = 0, end = 1; current.add(s.substring([1], end + 1));
Attempts:
3 left
💡 Hint
Common Mistakes
Using end as start index causes wrong substring extraction.
Using 0 or 1 as start index ignores the actual start position.
✗ Incorrect
substring(start, end + 1) extracts substring from start to end inclusive.
3fill in blank
hardFix the error in the backtracking recursive call to explore next partitions.
DSA Java
private void backtrack(String s, int start, List<String> current, List<List<String>> result) {
if (start == s.length()) {
result.add(new ArrayList<>(current));
return;
}
for (int end = start; end < s.length(); end++) {
if (isPalindrome(s, start, end)) {
current.add(s.substring(start, end + 1));
backtrack(s, [1], current, result);
current.remove(current.size() - 1);
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using start + 1 causes infinite recursion or wrong partitions.
Using end causes overlapping substrings.
✗ Incorrect
After choosing substring s[start:end], next start index is end + 1 to avoid overlap.
4fill in blank
hardFill both blanks to complete the main function that starts backtracking and returns all partitions.
DSA Java
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
List<String> current = new ArrayList<>();
[1](s, 0, current, result);
return [2];
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning current instead of result returns incomplete data.
Calling partition recursively causes stack overflow.
✗ Incorrect
Call backtrack to fill result, then return result list.
5fill in blank
hardFill all three blanks to create a map comprehension that stores substring lengths for palindromes.
DSA Java
Map<String, Integer> palindromeLengths = new HashMap<>(); for (int i = 0; i < s.length(); i++) { for (int j = i; j < s.length(); j++) { if ([1](s, i, j)) { palindromeLengths.put(s.[2](i, j + 1), j - i + [3]); } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using length instead of substring causes errors.
Not adding 1 to length calculation gives wrong length.
✗ Incorrect
Use isPalindrome to check, substring to get string, length calculation adds 1 for inclusive end.
