0
0
DSA Typescriptprogramming~10 mins

Recursion on Arrays and Strings in DSA Typescript - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to return the length of the string using recursion.

DSA Typescript
function recursiveLength(str: string): number {
  if (str === "") {
    return 0;
  }
  return 1 + recursiveLength(str[1]);
}
Drag options to blanks, or click blank then click option'
A.slice(1)
B.charAt(1)
C.substring(0, 1)
D.length
Attempts:
3 left
💡 Hint
Common Mistakes
Using str.length instead of slicing the string.
Using substring(0,1) which returns the first character, not the rest.
2fill in blank
medium

Complete the code to check if an array contains a target value using recursion.

DSA Typescript
function contains(arr: number[], target: number, index: number = 0): boolean {
  if (index === arr.length) {
    return false;
  }
  if (arr[1] === target) {
    return true;
  }
  return contains(arr, target, index + 1);
}
Drag options to blanks, or click blank then click option'
A.index
B[index]
C(index)
D{index}
Attempts:
3 left
💡 Hint
Common Mistakes
Using dot notation which is invalid for array indexing.
Using parentheses which is function call syntax.
3fill in blank
hard

Fix the error in the recursive function that reverses a string.

DSA Typescript
function reverseString(str: string): string {
  if (str.length === 0) {
    return "";
  }
  return reverseString(str[1]) + str.charAt(0);
}
Drag options to blanks, or click blank then click option'
A.slice(1)
B.charAt(1)
C.substring(1)
D.slice(0, 1)
Attempts:
3 left
💡 Hint
Common Mistakes
Using substring(1) works but slice(1) is preferred for clarity.
Using slice(0,1) returns the first character, not the rest.
4fill in blank
hard

Fill both blanks to create a recursive function that sums all elements in an array.

DSA Typescript
function sumArray(arr: number[], index: number = 0): number {
  if (index [1] arr.length) {
    return 0;
  }
  return arr[2] + sumArray(arr, index + 1);
}
Drag options to blanks, or click blank then click option'
A<
B>
C[index]
D.length
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '<' in the base case condition.
Using dot notation instead of square brackets for array access.
5fill in blank
hard

Fill all three blanks to create a recursive function that counts how many times a character appears in a string.

DSA Typescript
function countChar(str: string, char: string, index: number = 0): number {
  if (index [1] str.length) {
    return 0;
  }
  const count = (str.charAt(index) === char) ? [2] : 0;
  return count + countChar(str, char, index [3] 1);
}
Drag options to blanks, or click blank then click option'
A<
B1
C+
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '<' in the base case.
Adding 0 instead of 1 when characters match.
Using '-' instead of '+' to increment index.