Discover how a simple trick can turn a big problem into tiny, easy steps!
Why Recursion on Arrays and Strings in DSA Typescript?
Imagine you have a long list of names or a long word, and you want to find if a certain name or letter is inside it. Doing this by checking each item one by one can take a lot of time and effort, especially if the list or word is very long.
Checking each item manually means you have to remember where you stopped, and it's easy to make mistakes like skipping items or checking the same item twice. It also takes a lot of steps and can be confusing when the list or word is very long.
Recursion helps by breaking the problem into smaller, similar problems. Instead of checking the whole list at once, it checks one item and then asks itself to check the rest. This way, the problem becomes simpler and easier to manage, like solving a puzzle piece by piece.
function findItem(list: string[], target: string): boolean {
for (let i = 0; i < list.length; i++) {
if (list[i] === target) return true;
}
return false;
}function findItemRecursive(list: string[], target: string, index = 0): boolean { if (index === list.length) return false; if (list[index] === target) return true; return findItemRecursive(list, target, index + 1); }
Recursion on arrays and strings lets you solve complex problems by breaking them down into simple, repeatable steps that are easy to understand and manage.
Think of searching for a word in a book by checking one page at a time, and if not found, moving to the next page automatically until the word is found or the book ends.
Manual checking is slow and error-prone for long lists or strings.
Recursion breaks the problem into smaller, easier parts.
This approach makes complex tasks simpler and more reliable.
Practice
Solution
Step 1: Understand recursion on arrays
Recursive functions on arrays call themselves with smaller parts of the array to solve the problem step-by-step.Step 2: Identify the base case
The recursion stops when the array is empty or has one element, which is the base case.Final Answer:
It calls itself with a smaller part of the array until a base case is reached. -> Option DQuick Check:
Recursion = smaller parts + base case [OK]
- Thinking recursion loops without calling itself
- Confusing recursion with iteration
- Believing recursion only works on strings
Solution
Step 1: Check base case correctness
The base case should return 0 when array is empty to stop recursion correctly.Step 2: Check recursive call and addition
The function adds the first element to the sum of the rest of the array recursively.Final Answer:
function sum(arr: number[]): number { if(arr.length === 0) return 0; return arr[0] + sum(arr.slice(1)); } -> Option CQuick Check:
Base case returns 0 + recursive sum [OK]
- Missing base case causing infinite recursion
- Returning wrong base case value like 1
- Not adding the first element before recursive call
function reverseString(s: string): string {
if (s === "") return "";
return reverseString(s.slice(1)) + s[0];
}
console.log(reverseString("abc"));Solution
Step 1: Trace recursive calls
reverseString("abc") calls reverseString("bc") + "a"; reverseString("bc") calls reverseString("c") + "b"; reverseString("c") calls reverseString("") + "c".Step 2: Build return values from base case
reverseString("") returns ""; so reverseString("c") returns "" + "c" = "c"; reverseString("bc") returns "c" + "b" = "cb"; reverseString("abc") returns "cb" + "a" = "cba".Final Answer:
"cba" -> Option AQuick Check:
Reverse "abc" = "cba" [OK]
- Confusing order of concatenation
- Forgetting base case returns empty string
- Expecting original string as output
function countOccurrences(arr: number[], target: number): number {
if (arr.length === 0) return 0;
if (arr[0] === target) return 1 + countOccurrences(arr.slice(1), target);
}Solution
Step 1: Check base case and recursive calls
Base case returns 0 correctly when array is empty. When arr[0] equals target, function returns 1 plus recursive call.Step 2: Identify missing return for else case
If arr[0] is not target, function does not return anything, causing undefined result and error.Final Answer:
Missing else case to handle when arr[0] !== target -> Option AQuick Check:
All paths must return a value [OK]
- Forgetting else return causes undefined
- Changing base case incorrectly
- Thinking recursion is not needed
[1, [2, [3, 4], 5], 6], which recursive approach correctly flattens it into [1, 2, 3, 4, 5, 6]?Solution
Step 1: Understand nested array flattening
Flattening requires checking each element; if it is an array, recursively flatten it to handle any depth.Step 2: Build flattened array by concatenation
For non-array elements, add directly; for arrays, concatenate their flattened results to build final flat array.Final Answer:
Check if element is array; if yes, recursively flatten it and concatenate; else add element to result. -> Option BQuick Check:
Recursion handles any depth flattening [OK]
- Flattening only one level deep
- Not checking if element is array
- Using loops without recursion for nested arrays
Ready to prove it?
Pass the test and this pattern moves unknown
