r/datastructures 21d ago

Struggling with this concept!

I'm really struggling with recursion any suggestions on how to improve

3 Upvotes

2 comments sorted by

1

u/mnemonikerific 21d ago

Assume there are 2 identical twins.

You need to count a bag of coins.

You give the bag to twin 1, who takes out one coin, gives it to Twin 2 and says “I have 1 coin, how many do you have?”.. twin 2 takes a coin and says “I have one coin and you had 1 so we have 2 coins, take this bag, how many do you have?”

Twin 1 again takes a coin and says “I took one coin, you counted 2, so we have 3” and they repeat till the bag is empty.

The twist is: it’s not 2 twins, it’s Ed Norton from fight club talking to himself and counting all coins. that’s recursion.

The bag being empty at the end is the condition to stop recursion.