<aside> 💡 Identification
Any problem that requires a Choice → Desision pattern repeatedly is a recursion problem
</aside>
To Identify recursion, you have to recognose if you can identify a Decision Space. If you can identify a decision space, it is a recursion problem
We do not make input smaller in Recursion. We take a decision and a by product the input size gets smaller
Decision making is Primary.
If you can design a recursive tree, it is a recursion problem
For Example:
Give all the subsets that can be formed by the string “abc”
We have three choices. a , b , c
We can have mave multiple decisions from these choices.
With each Decision, the Input size decreases for the next recursive call.
Suppose we select ‘a’ for the current set, then only b , c remains for the next step.
Lets draw a recursive tree to show this.
After identifying a recursion problem, we can go either of the following two ways
Try to create a Hypothesis. If you fail, try to draw a diagram containing the input and output at different levels
Example:
Write a Function to print 1 to N using Recursion
function printTill(n-1)
that has our answer.function printTill(1)
function printTill(n-1)
what shall we do?function printTill(n) {
if(n==1) console.log(n) // Base Condition
printTill(n-1) // Hypothesis
console.log(n) // Induction
}
Approach:
We would try to approach this problem with the Base Case → Hypothesis → Induction method
Base case:
Q: What is the smallest valid input of this problem?
A: An empty input array
Q: What is the output for this input?
A: Empty Array
Hypothesis:
Q: Suppose our function sortArray(nums)
returned a sorted array, and you had to insert another number in this sorted Array, what would you do?
A: We would have to perform the following steps:
temp
variablesortArray(nums)
on the subarray exclusing the last numbertemp
and sortArray(nums)
into an insert(num, arr)
function that inserts a number in a sorted arrayInduction
Q. We saw that insert() function in the last step. We need to design that function
A: design an insert
function that takes in two arguments,
var sortArray = function(nums) {
if(!nums.length) return []
};
var sortArray = function(nums) {
if(!nums.length) return []
let temp = nums[nums.length-1]
return insert(temp, sortArray(nums.slice(0, nums.length-1)))
};
function insert(num, arr) {
if(!arr || !arr.length) return [num]
for(let i=0; i<arr.length; i++) {
if(arr[i]>=num){
return [...arr.slice(0, i), num, ...arr.slice(i)]
}
}
}