Sum of First N Numbers

Pattern: Recursion basics

easy

Add 1 + 2 + ... + n recursively, as n plus the sum of the numbers below it, and watch the calls stack up and unwind.

The problem

You are given a whole number n from 0 to 500. Return 1 + 2 + ... + n, the sum of the first n positive whole numbers, using recursion. The sum for 0 is 0. For example, the answer for 5 is 15.

On the original site the problem is written a little differently, so use the link above for its exact wording. The function name sumOfN and the limit of 500 are this guide's own. The limit keeps the recursion shallow enough for Python's default depth limit.

Think first

  • If someone tells you the sum of 1 to 4 is 10, how do you get the sum of 1 to 5 in one step?
  • Which value of n has an answer you know without any work?
  • How many calls will be open at once for n = 5?

Hints

    Brute force, and why it fails

    A loop that adds 1, 2, ..., n works and uses no stack. Even better, the formula n × (n + 1) / 2 gives the answer in one step: for 5 it is 5 × 6 / 2 = 15. Outside this exercise that formula is the best answer.

    The point here is different: this is the simplest possible recursion, so it is the place to see the base case, the step and the call stack clearly before they are needed for problems that have no formula.

    The key insight

    Describe the answer for n using the answer for n - 1, and give one case (n = 0) that needs no further call. The calls go down to 0, and the sums come back up.

    Dry run

    sumOfN(3)0 
    waiting3 + ?

    Call sumOfN(3). 3 is not 0, so it needs 3 + sumOfN(2) and waits. The array is the call stack, oldest call on the left.

    Step 1 of 7

    The plan

    function sumOfN(n):
        if n == 0:
            return 0                  # base case
        return n + sumOfN(n - 1)      # smaller problem, plus my part
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    There are n + 1 calls, each doing constant work. All of them are open at the deepest point, so the call stack holds n + 1 frames.

    Edge cases

    • n = 0 returns 0 straight from the base case.
    • n = 1 makes one recursive call.
    • n = 500 goes 501 calls deep, well within Python's default limit of about 1000.
    I've built my logic, show the code

    Java

    class Solution {
        public int sumOfN(int n) {
            if (n == 0) {
                return 0;               // base case: nothing to add
            }
            return n + sumOfN(n - 1);   // n plus the sum of everything below it
        }
    }

    C++

    class Solution {
    public:
        int sumOfN(int n) {
            if (n == 0) {
                return 0;               // base case: nothing to add
            }
            return n + sumOfN(n - 1);   // n plus the sum of everything below it
        }
    };

    Python

    class Solution:
        def sumOfN(self, n):
            if n == 0:
                return 0                    # base case: nothing to add
            return n + self.sumOfN(n - 1)   # n plus the sum of everything below it

    Common mistakes

    • Leaving out the base case, so the calls go on to -1, -2, ... until the stack overflows.
    • Writing sumOfN(n - 1) without return or without adding n, so the sum is lost.
    • Using recursion for very large n in Python, which hits the depth limit. The formula or a loop has no such limit.

    Similar problems