Skip to content

2011. Final Value of Variable After Performing Operations 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
 public:
  int finalValueAfterOperations(vector<string>& operations) {
    int ans = 0;

    for (const string& op : operations)
      ans += op[1] == '+' ? 1 : -1;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
  public int finalValueAfterOperations(String[] operations) {
    int ans = 0;

    for (final String op : operations)
      ans += op.charAt(1) == '+' ? 1 : -1;

    return ans;
  }
}
1
2
3
class Solution:
  def finalValueAfterOperations(self, operations: list[str]) -> int:
    return sum(op[1] == '+' or -1 for op in operations)