Stack sum function

Given a stack of integers, the function returns the sum of the elements in the stack.

Problem

Given a stack of integers, write a function that returns the sum of the elements in the stack.
Example input: [1, 2, 3, 4, 5]
Example output: 15

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:
// The optimal solution is to use a for loop to iterate through the stack and add each element to a variable.
// This is optimal because it is O(n) time complexity and O(1) space complexity.

function sumStack(stack) {
  let sum = 0;
  for (let i = 0; i < stack.length; i++) {
    sum += stack[i];
  }
  return sum;
}

// Test Cases:
console.log(sumStack([1, 2, 3, 4, 5])); // 15
console.log(sumStack([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])); // 55
console.log(sumStack([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])); // 120

A.I. Evaluation of the Solution

The candidate's solution is correct and solves the problem. The approach is straightforward and easy to understand. The time complexity of the solution is O(n) and the space complexity is O(1).

Evaluated at: 2022-12-11 00:15:33