FastPrepChecked Recursive Sum

Checked Recursive Sum

Headlands Technologies logoHeadlands Technologies● EasyFULLTIMEPHONE SCREEN
Learn

Problem statement

Given a nonnegative integer n, compute the sum of every integer from 1 through n. The sum for n == 0 is 0.

For this exercise, the result must fit in the logical signed 32-bit range from 0 through 2147483647. Return -1 when the exact sum exceeds this range. Do not wrap, clamp or take a modulus. Design checks so no intermediate integer overflows, without relying on a wider integer type.

Implement a recursive summation approach with a safe stack depth, then express the tail-recursive accumulator state as a portable constant-stack loop. A call appearing last in source code does not guarantee that the runtime eliminates its stack frame. The loop preserves the state transition without relying on compiler tail-call optimization.

This interface and the -1 result choose one of the reported follow-up conventions. They do not claim an original interview width, error API or compiler guarantee.

Function

checkedSumUpTo(n: int) → int

Examples

Example 1

n = 5return = 15

The sum is1+2+3+4+5=15.

Example 2

n = 65535return = 2147450880

The exact sum2147450880is below2147483647, so it can be returned as a signed32-bit integer.

Example 3

n = 65536return = -1

The exact sum2147516416exceeds2147483647, so return the authored overflow sentinel-1.

Constraints

  • 0 <= n <= 2147483647.
  • All inputs are valid. The return type is a logical signed32-bit integer.
  • If the exact sum fits, return it exactly. Otherwise return -1.
  • Use checked arithmetic or division comparisons within this logical range; Python arbitrary-size integers and Go machine-sized integers must follow the same explicit result limit.
  • The interface, zero-input behavior, width and sentinel are authored practice conventions.

More Headlands Technologies problems

See Headlands Technologies hiring insights
public int checkedSumUpTo(int n) {
    // write your code here
}
n5
expected15
Checking account…