Day 21: "Let's Tackle Recursion"

Day 21: "Let's Tackle Recursion"

·

2 min read

What in the what is recursion?!

This is my 1st time encountering and working with recursion and let's just say, I'll need a bit more practice before fully understanding what these lines of code are doing. Theoretically, I seem to understand it but using it in practice will be the obstacle I need to tackle.

So what is recursion? ...

Recursion is a function that calls itself until a "base case" is true. The problem is broken down into smaller instances of the same problem. You can look at it like the Russian dolls, they get smaller and smaller until you reach the "prize" or in this case, the "base case"

Recursion can be similar to iteration but you only use iteration when you need to repeat a block of code a specific number of times or until a condition is met. Whereas recursion is used when the problem can be broken down into smaller instances of the same problem and you have a clear base. Often used for problems like traversing trees and finding combinations.

After the base case is met, the recursive function starts returning values and "unwinding". As it unwinds, the functions are taken off of the stack. Values are returned in reverse order. This function has a LIFO ( last in, first out) data structure.

One of the simplest ways to see recursion used is reversing a string.

Here's a bit of an explanation of what's going on in this problem:

  1. When we call reverseString('hello'), it executes reverseString('ello') + 'h'

  2. Now, reverseString('ello') calls reverseString('llo') + 'e'

  3. Next, reverseString('llo') calls reverseString('lo') + 'l'

  4. In the next call, reverseString('lo'), calls reverseSTring('o') + 'l'

  5. Finally, reverseString('o') returns 'o'.

Now, the function can start "unwinding" the recursion and concatenating the characters to form the reversed string:

  1. 'o' + 'l' gives 'ol'.

  2. 'ol' + 'l' gives 'oll'.

  3. 'oll' + 'e' gives 'olle'.

  4. 'olle' + 'h' gives 'olleh'.

While this is still very new to me, taking Brad Traversy's course is really helping me get through learning about DSA in depth. From his lessons I have learned how to reverse strings in three different ways, using built-in functions, reversing a for loop, and now using recursion.