PPractick

DSA interview question

Sum of First N Numbers Using Recursion

Easy · Algorithms · Topics: recursion, functional

The problem

A fitness app awards points on a rising scale: 1 point on day 1, 2 on day 2, and so on, and it needs the total after N days, which is 1 + 2 + ... + N. There's a famous formula for it, but the exercise is to compute it recursively in two styles: parameterised recursion, where a running sum is carried along as an argument, and functional recursion, where each call returns its answer built from the smaller call's answer. The difference between "carry the result down" and "build the result on the way back up" is the core idea behind every recursive DP later on.

Example: N = 5 → 1 + 2 + 3 + 4 + 5 = 15.

Function signature

long long sumParameterised(int n, long long acc = 0);  // carries the running sum
long long sumFunctional(int n);                        // returns n + sum(n - 1)

Test cases

Input nOutputExplanation
5151 + 2 + 3 + 4 + 5
11
00Empty sum
1005050Matches n(n + 1) / 2
100005000500010,000 levels of recursion; fine for the default stack

(Confirm: 0 ≤ n ≤ 10^4 so the recursion depth is safe; the result can also be checked against n(n + 1) / 2.)

How interviewers phrase it

Clarifying questions to ask

  1. Must it be recursive, or is the formula acceptable?
  2. How large can N be? (Recursion depth and overflow.)
  3. Can N be 0?

Follow-ups to expect

  1. "Parameterised vs functional?"
  2. "Which one is tail recursive?"
  3. "Can you do it in O(1)?"
  4. "Why long long?"
  5. "Complexity of the recursive versions?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in