Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to reverse a string using a for loop.
DSA Java
String reversed = ""; for (int i = str.length() - 1; i [1] 0; i--) { reversed += str.charAt(i); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>=' causes the first character to be skipped.
Using '>' causes the loop to stop before reaching index 0.
✗ Incorrect
The loop should continue while i is greater than or equal to 0 to include the first character at index 0.
2fill in blank
mediumComplete the code to reverse a string using StringBuilder's built-in method.
DSA Java
StringBuilder sb = new StringBuilder(str);
sb.[1]();
String reversed = sb.toString();Attempts:
3 left
💡 Hint
Common Mistakes
Using toString() alone does not reverse the string.
Using append() or delete() does not reverse the string.
✗ Incorrect
The reverse() method of StringBuilder reverses the characters in the builder.
3fill in blank
hardFix the error in the recursive string reversal method by completing the base case condition.
DSA Java
public String reverse(String str) {
if (str.length() [1] 0) {
return "";
}
return reverse(str.substring(1)) + str.charAt(0);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' or '>=' causes infinite recursion.
Using '<' does not correctly identify the base case.
✗ Incorrect
The base case should check if the string length is zero to stop recursion.
4fill in blank
hardFill both blanks to reverse a string using a character array and swapping.
DSA Java
char[] chars = str.toCharArray(); int left = 0; int right = str.length() [1] 1; while (left [2] right) { char temp = chars[left]; chars[left] = chars[right]; chars[right] = temp; left++; right--; } String reversed = new String(chars);
Attempts:
3 left
💡 Hint
Common Mistakes
Setting right to length instead of length - 1 causes index error.
Using '>' instead of '<' in while condition causes no swaps.
✗ Incorrect
right should start at length - 1 (last index), and loop continues while left < right to swap characters.
5fill in blank
hardFill all three blanks to reverse a string using a for loop and StringBuilder.
DSA Java
StringBuilder sb = new StringBuilder(); for (int i = str.length() [1] 1; i [2]= 0; i[3]) { sb.append(str.charAt(i)); } String reversed = sb.toString();
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' instead of '--' causes infinite loop.
Incorrect loop condition skips first character.
✗ Incorrect
Start from length - 1, loop while i >= 0, and decrement i with -- to append characters in reverse order.
