Recursion Introduction
Recursion Introduction
CRASH
CAMP
RECURSION
Introduction
LET'S
THINK
RECURSIVLEY
Ruyank: Bhaiyaa can you help me to overcome 'fear' of
'Recursion' pls ?
0 1 2
2 1 3
Bhaiyaa: Okay that was pretty simple and also the intuitive
solution but can you think of some other approach ?
Bhaiyaa: I'm giving you below array & make a function which
returns me sum of this array
0 1 2
2 1 3
1 3
Ruyank: Now bhaiyaa, if you take away idx=2 out as well then
we aren't remaining with any array, what to do then?
2
3
Bhaiyaa: Don't worry about that now, we will see that later
BTW you will make sum4(arr, 3, 2) finally and since
l(3) > h(2), you can say- you traversed entire array
& you can return 0
To give you some idea, your sum4() was handling base
case in terms of Recursion, but we will see later.
2
sum2(nums,1,2) 1 3
1
sum3(nums,2,2) 3
sum4(nums,3,2)
sum1(nums, l, h)
return nums[0] + sum2(nums,1,2)
sum2(nums, l, h)
return nums[1] + sum3(nums,2,2)
sum3(nums, l, h)
return nums[2] + sum4(nums,3,2)
sum4(nums, l, h)
return 0
Bhaiyaa: Ruyank, why do we make functions ?
sum(nums, l, h)
return nums[0] + sum(nums,1,2)
sum(nums, l, h)
return nums[1] + sum(nums,2,2)
sum(nums, l, h)
return nums[2] + sum4(nums,3,2)
sum4(nums, l, h)
return 0
Ruyank: When our test case crosses it's valid boundary, here
it was valid till l <= h & as soon as l becomes > h,
we know we are done with array so we just did
return 0; // when nothing left in array sum = 0
sum(nums, l, h)
return nums[0] + sum(nums,1,2)
sum(nums, l, h)
return nums[1] + sum(nums,2,2)
sum(nums, l, h)
return nums[2] + sum4(nums,3,2)
sum(nums, l, h)
return 0
Bhaiyaa: Ruyank, can you see above diagram now and get some
idea that what exactly we did ?
Ruyank: Earlier we used sum1(),sum2(),sum3(),sum4() to
calculate the sum of array but now we just have
sum() & we are reusing it all the time
sum1(nums, l, h)
return nums[0] + sum2(nums,1,2)
sum2(nums, l, h)
return nums[1] + sum3(nums,2,2)
sum3(nums, l, h)
return nums[2] + sum4(nums,3,2)
sum4(nums, l, h)
return 0
sum(nums, l, h)
return nums[0] + sum(nums,1,2)
sum(nums, l, h)
return nums[1] + sum(nums,2,2)
sum(nums, l, h)
return nums[2] + sum(nums,3,2)
sum(nums, l, h)
return 0
OR
sum(nums, l, h)
if(l > h) return 0
return nums[l] + sum(nums,l+1,h)