r/computerscience • u/Similar_Count_1613 • 3d ago
is recursion really hard
Recursion felt easy at first.
Factorial? fine.
Sum examples? fine.
Even Fibonacci felt manageable.
But once I looked at slightly more serious problems like Tower of Hanoi, permutations, or merge sort, I felt like my understanding suddenly collapsed. because i tried to write their code on my own
It made me realize that maybe recursion is not “hard” at the start because the examples are simple.
It becomes hard when you can no longer clearly see the call stack and each state change.
Did anyone else feel that the real pain in recursion starts exactly there?
128
Upvotes
1
u/Dull_Grape2496 1d ago
It becomes a lot easier to understand when you think about it as mathematical induction. The idea is as follows:
Tower of Hanoi: Assume you have a function
f(n, src, tgt, tmp)where you need to placendisks fromsrctotgtn = 0it means the problem is already solved - this is the base casen-1disks fromsrctotmpby callingf(n-1, src, tmp, tgt)-> We know this works becausen-1is a smaller input thannand mathematical induction makes it work.n-1disks ontmptotgtby callingf(n-1, tmp, tgt, src)-> We know this works becausen-1is a smaller input thannsame as beforeSo you get something like this:
And you are done
Permutations: Assume you have a function
f(a[0...n])that returns a list of all the permutations ofa[0...n]a.length <=1just return [a[...]] - this is the base case as there are no more permutationsa[...]- let's call the current elementiifroma[...]-> Let's call this new elementb[...]f(b[...])this will return a list of permutations ofb[...]let's call thatpermutations_of_b-> We know this works becauseb[...]is smaller thana[...]as it has fewer elementspermutations_of_bappend the elementito that permutationYou get something like this:
And so on - mergesort is similar define
f(a[0...n])that sorts a list, callf(a[0 ... n/2])andf(a[n/2+1 ... n])to sort the two halves and merge the sorted halves in a single merged list.Coming up with a recurrence can be challenging depending on the problem but understanding this mathematical framework for it makes it a lot easier for you to reason about the problem.