Recursion
Coding Interview Concepts : Deep Dive
explained
in 5
minutes
Find more
interview tips ->
[Link]
Introduction
Imagine your team at work gives you a gift box
for your birthday!
You are told that the gift is inside the box.
When you open it, instead of finding the gift, you
find two smaller boxes inside.
Find more
interview tips ->
[Link]
Boxes inside boxes?
When you open the two smaller boxes, one has the
gift, but the other has another smaller box inside.
Technically, your team didn’t lie. The gift was just in
smaller boxes, which were inside larger boxes.
In recursion, we encounter two types of boxes
Boxes with values inside (no more smaller boxes
inside
Boxes containing more boxes (that need to be
opened)
Find more
interview tips ->
[Link]
Making sense of the
analogy
These two type of boxes are analogous to the
two key components of recursion:
Base Case: Boxes that contain values directly.
These are our stopping points.
Recursive Case: Boxes that contain more
boxes. These require further "unwrapping".
Base Case (Smallest box
with values inside)
Recursive Case (Big box
with smaller boxes)
Recursive Case (Big box
with smaller boxes)
Find more
interview tips ->
[Link]
Fibonacci Sequence
F(3) F(2) + F(1)
1
F(1) + F(0)
1 0
A perfect example for understanding recursion
0th Fibonacci number =
1st Fibonacci number =
Each subsequent number = sum of previous two
F(n) = F(n-1) + F(n-2)
Find more
interview tips ->
[Link]
Base Cases
F(1) + F(0)
1 0
Only the smallest boxes have values inside them.
F(1) = 1 and F(0) = 0.
These are our base cases. Without them, we
wouldn’t be able to do any calculations as there
would be no stopping point.
If we don’t include the base case, our
function would loop forever.
This takes care of “boxes with values”
Find more
interview tips ->
[Link]
Recursive Case
This is the part where the function calls itself.
This is treated as its own function - it’s calling
the original function with a smaller input.
In other words, every subproblem is treated
as its own problem.
Recursive
fib(3)
Base
fib(2) fib(1) = 1
fib(1) = 1 fib(0) = 0
The recursive case persists until we hit the base
case.
This takes care of “boxes inside
boxes” example.
Find more
interview tips ->
[Link]
Tackling Recursive
Problems
Identify clear base cases
Ensure each recursive call moves toward a base
case
Break complex problems into similar smaller
problems
Trust that the recursion will handle the details
Find more
interview tips ->
[Link]
Join 100k+ Daily
NeetCoders Preparing
for coding interviews
[Link]