Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to reverse a string using built-in methods.
DSA Javascript
function reverseString(str) {
return str.split('').[1]().join('');
}Attempts:
3 left
💡 Hint
Common Mistakes
Using sort() instead of reverse() changes order alphabetically, not reverses.
Using map() or filter() does not reverse the array.
✗ Incorrect
The split('') method converts the string into an array of characters. The reverse() method reverses the array. Then join('') combines the characters back into a string.
2fill in blank
mediumComplete the code to reverse a string using a for loop.
DSA Javascript
function reverseString(str) {
let reversed = '';
for (let i = str.length - 1; i [1] 0; i--) {
reversed += str[i];
}
return reversed;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' or '<=' causes the loop to never run or run incorrectly.
Using '>' excludes the first character at index 0.
✗ Incorrect
The loop starts from the last index (str.length - 1) and continues while i >= 0 to include the character at index 0.
3fill in blank
hardFix the error in the recursive string reversal function.
DSA Javascript
function reverseString(str) {
if (str.length === 0) {
return '';
}
return reverseString(str.slice(1)) + str[1](0);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using slice(0) returns the entire string, causing infinite recursion.
substr and substring can work but are less clear for single character extraction.
✗ Incorrect
To get the first character of the string, charAt(0) is the correct method. Using slice(0) returns the whole string, causing infinite recursion.
4fill in blank
hardFill both blanks to create a reversed string using reduce.
DSA Javascript
function reverseString(str) {
return str.split('').[1]((acc, char) => char [2] acc, '');
}Attempts:
3 left
💡 Hint
Common Mistakes
Using concat instead of '+' may cause errors since concat is for arrays.
Adding accumulator before char reverses the string incorrectly.
✗ Incorrect
The reduce method accumulates characters in reverse order by adding the current character before the accumulator. Using '+' concatenates strings.
5fill in blank
hardFill the first two blanks to reverse a string using a while loop.
DSA Javascript
function reverseString(str) {
let reversed = '';
let i = str.length [1];
while (i [2] 0) {
reversed += str[i];
i--;
}
return reversed;
}Attempts:
3 left
💡 Hint
Common Mistakes
Starting i at str.length causes out-of-bounds access.
Using '>' excludes the character at index 0.
Incorrect indexing inside loop causes wrong characters.
✗ Incorrect
Start i at str.length - 1 (last index). Loop while i >= 0 to include all characters including index 0.
