Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to reverse the array using the built-in method.
DSA Typescript
const arr = [1, 2, 3, 4, 5]; arr.[1](); console.log(arr);
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'sort()' which sorts the array instead of reversing it.
Using 'map()' or 'filter()' which do not reverse the array.
✗ Incorrect
The built-in method to reverse an array in TypeScript is 'reverse()'.
2fill in blank
mediumComplete the code to reverse the array by swapping elements using a for loop.
DSA Typescript
const arr = [10, 20, 30, 40, 50]; for(let i = 0; i < arr.length / 2; i++) { const temp = arr[i]; arr[i] = arr[arr.length - 1 - [1]]; arr[arr.length - 1 - i] = temp; } console.log(arr);
Attempts:
3 left
💡 Hint
Common Mistakes
Using a fixed number instead of the loop index.
Using 'arr.length' which is out of array bounds.
✗ Incorrect
To swap elements from start and end, use the same index 'i' for both positions.
3fill in blank
hardFix the error in the recursive function to reverse an array.
DSA Typescript
function reverseArray(arr: number[], start: number, end: number): void {
if (start >= end) return;
const temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
reverseArray(arr, start + 1, [1]);
}
const array = [1, 2, 3, 4, 5];
reverseArray(array, 0, array.length - 1);
console.log(array);Attempts:
3 left
💡 Hint
Common Mistakes
Keeping the end index the same, which results in incorrect reversal.
Increasing the end index, which goes out of bounds.
✗ Incorrect
The recursive call should increment the start pointer and decrement the end pointer: start + 1, end - 1.
4fill in blank
hardFill both blanks to create a new reversed array using a for loop.
DSA Typescript
const original = [5, 10, 15, 20]; const reversed = []; for(let i = original.length - 1; i [1] 0; i--) { reversed.[2](original[i]); } console.log(reversed);
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' which skips the first element at index 0.
Using 'pop()' which removes elements instead of adding.
✗ Incorrect
The loop runs while i is greater than or equal to 0, and elements are added to reversed using push().
5fill in blank
hardFill all three blanks to reverse an array using the reduce method.
DSA Typescript
const arr = [2, 4, 6, 8]; const reversed = arr.[1](([2], [3]) => [[3]].concat([2]), []); console.log(reversed);
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'map' instead of 'reduce' which does not accumulate.
Swapping 'acc' and 'current' causing incorrect order.
✗ Incorrect
The reduce method is used to accumulate elements in reverse order by concatenating current element before accumulator.
