Question Bank
/

Space Complexity Quiz

Space Complexity Quiz

Three short prompts on space accounting: stack vs heap usage, recursion depth, and an in-place vs out-of-place comparison.

Question Bank
Easy
JavaScript
3 questions
space-complexity
asymptotic-analysis
quiz
fundamentals

393 views

6

What is the space complexity (extra space beyond the input) of this function and why?

Examples

Example 1:

Input: n = 12345
Output: 15
Explanation: 1 + 2 + 3 + 4 + 5 = 15. Only two scalars (sum and n) live across iterations regardless of input size, so extra space is O(1). Time is O(log n) because each step strips one decimal digit.
function sumDigits(n) {
    let sum = 0;
    while (n > 0) {
        sum += n % 10;
        n = Math.floor(n / 10);
    }
    return sum;
}