Data structures and algorithm play an important role in any programming job interview. It is important because it consists of basic programming concept which every programmer should know by default like stack, queue, linked list, array, tree and graph. Actually algorithm are way to solve problems using above mentioned data structures. There may be many ways or algorithms to solve the problem. Recursion is method where the solution to a problem depends on solutions to smaller instances of the same problem. Generally people find 2-3 line recursive solution and memorise it but they don’t understand what happening inside the recursive call how scope and values of the variable changing inside the small piece of code.
So let’s understand what magic happens inside the tiny piece of recursive code. Recursion is basically dividing the main problem into sub-problem of the same type as original, solve the sub-problems and combine the results.
- Defintion : A functions that calls itself.
- Basic Conditions : 1. The base case
2. Recursive call - Types : 1. head Recursion.
- 2. Tail Recursion.
- Example :
def fun(number) if (number > 0) fun(--number) puts number fun(--number) end end
-
Output: 0 1 2 0 3 0 1
Explanation : Recursion Tree
fun(4) / fun(3), puts(3), fun(2)(puts 0 1) / fun(2), puts(2), fun(1)(puts 0) / fun(1), puts(1), fun(0)(does nothing) / fun(0), puts(0), fun(-1) (does nothing)
Explanation of head and tails Recursion :
Head Recursion : functions call itself before the other operation performed inside the function.
Tail Recursion : function call itself after the other operation performed inside the function.
Example :
def tail(number) def head(number)
if(number == 1) if(number == 0)
return number return number
else else
puts number head(number-1)
end end
tail(number-1); puts number
end end