Join waitlist
DSACommunity question

how do you trace recursion fast?

Asked by Nikhil Choudhary 1 month ago 2 answers 6 votes
int f(int n) {
    if (n <= 1) return 1;
    return f(n-1) + f(n-2);
}

f(4)? I keep messing up when drawing the full tree under time pressure

2 answers

Abhishek Dubey1 month agoMost voted6

Don't go top down, build up from the base case:
f(0)=1, f(1)=1, f(2)=2, f(3)=3, f(4)=5

Much faster than a tree.

aman khan1 month ago2

its just fibonacci shifted. quiz setters love hiding fibonacci

Related questions

Go deeper

Want the full explanation, not just an answer?

Structured lessons on DSA, core CS, Java and interview skills, each ending in a quiz so you know it stuck.