Problem · Array

Operator-First Array Calculator

Learn this problem
EasyAnduril logoAndurilFULLTIMEONSITE INTERVIEW

Problem statement

Given op equal to "+" or "-" and a non-empty array operands, evaluate the corresponding operator-first expression.

  • For "+", return the sum of every operand.
  • For "-", start with the first operand and subtract each later operand from left to right.

Function

calculate(op: String, operands: int[]) → long

Examples

Example 1

op = "+"operands = [1,2,3]return = 6

The expression is 1 + 2 + 3.

Example 2

op = "-"operands = [10,5,3]return = 2

Left-associative subtraction gives (10 - 5) - 3 = 2.

Example 3

op = "-"operands = [-4,-6,3]return = -1

The calculation is (-4 - (-6)) - 3 = -1.

Constraints

  • op is exactly "+" or "-".
  • 1 <= operands.length <= 200000.
  • -1000000000 <= operands[i] <= 1000000000.
  • The final answer fits a signed 64-bit integer.

More Anduril problems

drafts saved locally
public long calculate(String op, int[] operands) {
    // Write your code here.
}
op"+"
operands[1,2,3]
expected6
checking account