Fireship · @fireship
Recursion in 100 Seconds
Uploaded December 30, 2019 · Length 1:40
Summary
How to implement recursion in programming with examples and use cases.
- recursion
- programming
- algorithms
- functions
- tree traversal
- graph traversal
Transcript preview
The first 2 minutes of the transcript. Select a timestamp to watch that moment on YouTube.
- 0:00
a recursive function is a function that
- 0:02
calls itself inside of its own
- 0:04
definition it's like having a dream
- 0:06
inside of a dream when you have a
- 0:07
recursive function that calls itself
- 0:09
without anything to stop it you have
- 0:11
created an infinite Loop the first
- 0:13
function gets pushed onto the call stack
- 0:14
the next one on top of it then another
- 0:16
one on top of that and so on forever or
- 0:19
until your runtime throws a stack
- 0:20
Overflow error or the computer just runs
- 0:22
out of memory so recursion is just
- 0:24
another way to create a loop but
- 0:26
infinite Loops aren't very useful in
- 0:28
practice that's why recursive function
- 0:30
have some sort of stopping point like
- 0:32
some conditional logic that tells the
- 0:33
function to stop calling itself when a
- 0:35
condition has been met on an interview
- 0:37
you might be asked to implement some
- 0:38
code that finds a specific index in the
- 0:41
Fibonacci sequence you'll notice a given
- 0:43
index of the sequence is just the sum of
- 0:45
the two previous values so how do we
- 0:47
find index number 2023 your first
- 0:50
thought might be to implement an
- 0:51
iterative solution with a for Loop
- 0:53
compute the Fibonacci value for each
- 0:54
index until we get to the Target index
- 0:56
of 2023 but then you're asked to
- 0:59
implement a cursive solution we can do
- 1:01
that by writing a function that starts
- 1:03
with the index and then Works its way
- 1:04
backwards until it gets to a base case
- 1:07
of being less than or equal to one
- 1:09
notice how we're calling the same
- 1:10
function inside the function body and
- 1:12
we're doing it twice there's a big
- 1:14
problem here though it will Traverse
- 1:15
down the entire sequence for every
- 1:17
single index that's o to the N squ time
- 1:20
complexity which is not good at all in
- 1:21
the next video I'll explain how to
- 1:23
improve this with memorization recursive
- 1:25
functions are not the right choice in
- 1:26
every situation but they are very good
- 1:28
for tree and graph Travers rals this has
- 1:30
been recursion in 100 seconds thanks for
- 1:33
watching and I will see you in the next
- 1:35
one


