Sum 1..N — Accumulator vs Plain Recursion

Medium ⏱ 12 min 49% acceptance ★★★★★ 4.6
Implement sum_acc(n, acc=0) that sums the integers from 1 to n using the tail-recursive pattern: an accumulator parameter carries the running total forward with each call, so the addition happens *before* recursing rather than after the recursive call returns (unlike a naive n + sum_acc(n - 1)).

Examples

Example 1
Input
sum_acc(5)
Output
15
Explanation

1+2+3+4+5 = 15, accumulated as acc grows: 5,9,12,14,15.

Example 2
Input
sum_acc(0)
Output
0
Explanation

Base case returns the accumulator unchanged.

Constraints

  • n >= 0
  • The addition must happen before the recursive call (pass n + acc forward), not after it returns.

Topics

RecursionFunctions

Companies

SalesforceServiceNow

Hints

Hint 1

Base case: n == 0, return acc.

Hint 2

Recursive case: sum_acc(n - 1, acc + n) — note Python does not actually optimize tail calls, but the pattern still matters for reasoning about call structure.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.