Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the sum of all elements in the array using recursion.
DSA Javascript
function sumArray(arr) {
if (arr.length === 0) return 0;
return arr[0] + sumArray(arr[1]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() or shift() which modify the original array and cause incorrect recursion.
Using splice() which also modifies the original array.
✗ Incorrect
We use arr.slice(1) to get the array without the first element for the recursive call.
2fill in blank
mediumComplete the code to check if a string is a palindrome using recursion.
DSA Javascript
function isPalindrome(str) {
if (str.length <= 1) return true;
if (str[0] !== str[str.length [1] 1]) return false;
return isPalindrome(str.slice(1, -1));
}Attempts:
3 left
💡 Hint
Common Mistakes
Using + instead of - causes out of range index.
Using * or / operators are not valid for indexing.
✗ Incorrect
We compare the first and last characters using str.length - 1.
3fill in blank
hardFix the error in the recursive function that reverses a string.
DSA Javascript
function reverseString(str) {
if (str === '') return '';
return reverseString(str[1]) + str[0];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using array methods like pop() or shift() on strings causes errors.
✗ Incorrect
slice(1) returns the string without the first character, suitable for recursion.
4fill in blank
hardComplete the code to create a recursive function that counts how many times a character appears in a string.
DSA Javascript
function countChar(str, char) {
if (str.length === 0) return 0;
return (str[0] === char ? 1 : 0) + countChar(str[1], char);
}Attempts:
3 left
💡 Hint
Common Mistakes
Trying to modify the char parameter causes errors.
Using pop() or shift() on strings is invalid.
✗ Incorrect
We slice the string from index 1 for recursion and pass char unchanged.
5fill in blank
hardFill all three blanks to create a recursive function that builds an object mapping each word to its length from an array.
DSA Javascript
function mapWordLengths(words) {
if (words.length === 0) return {};
const rest = mapWordLengths(words[1]);
rest[words[0]] = words[0][2];
return rest;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() modifies the original array and causes errors.
Confusing the property assignment syntax.
✗ Incorrect
We slice the array from index 1, then assign the length of the first word to the object.
