Skip to content
We areTOP 1%
DSA · Beginner · Pattern 7 of 11

Recursion

11 problems.
Your progress0%
1st Visit
0/11
2nd Visit
0/11
Revise
0/11

About this pattern

A recursive function solves a problem by calling itself on smaller instances until it reaches a base case that is answered directly. Writing one comes down to three decisions: the base case, the smaller subproblem, and how to combine its result into the answer.

The pattern appears when a structure is defined in terms of itself (sequences, grammars, nested expressions), when the input can be halved as in fast exponentiation, or when every subset or sequence of choices must be enumerated for a small n, around 20 or fewer. Cost is the number of calls times the work per call; exponential enumeration is acceptable only for small inputs, and very deep recursion consumes stack memory.

// Shape of a recursive function.
long long solve(long long n) {
    if (n <= 1) return baseValue(n);        // 1. base case
    long long sub = solve(n / 2);           // 2. smaller instance
    return combine(sub, n);                 // 3. combine
}

// Enumerate all 2^n include/exclude choices.
void go(int i, const vector<int>& a, long long sum) {
    if (i == (int)a.size()) { check(sum); return; }
    go(i + 1, a, sum + a[i]);               // take a[i]
    go(i + 1, a, sum);                      // skip a[i]
}

Problems

Recursion questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1Fibonacci NumberLeetCodeEasy Solve Fibonacci Number on LeetCode (opens in a new tab)
2Sum in Binary TreeCodeforcesEasy 800Solve Sum in Binary Tree on Codeforces (opens in a new tab)
3Lucky DivisionCodeforcesEasy 1000Solve Lucky Division on Codeforces (opens in a new tab)
4Little Elephant and FunctionCodeforcesEasy 1000Solve Little Elephant and Function on Codeforces (opens in a new tab)
5Tavas and SaDDasCodeforcesEasy 1100Solve Tavas and SaDDas on Codeforces (opens in a new tab)
6Petr and a Combination LockCodeforcesEasy 1200Solve Petr and a Combination Lock on Codeforces (opens in a new tab)
7Pow(x, n)LeetCodeMedium Solve Pow(x, n) on LeetCode (opens in a new tab)
8Count Good NumbersLeetCodeMedium Solve Count Good Numbers on LeetCode (opens in a new tab)
9Sort an ArrayLeetCodeMedium Solve Sort an Array on LeetCode (opens in a new tab)
10K-th Symbol in GrammarLeetCodeMedium Solve K-th Symbol in Grammar on LeetCode (opens in a new tab)
11Find the Winner of the Circular GameLeetCodeMedium Solve Find the Winner of the Circular Game on LeetCode (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account