# Final Value of Variable After Performing Operations
**Difficulty:** EASY
[External](https://leetcode.com/problems/final-value-of-variable-after-performing-operations)
Canonical: https://scaleengineer.com/dsa/problems/final-value-of-variable-after-performing-operations
**Data structures:** Array, String
---
## Problem
There is a programming language with only **four** operations and **one** variable `X`:

* `++X` and `X++` **increments** the value of the variable `X` by `1`.
* `--X` and `X--` **decrements** the value of the variable `X` by `1`.

Initially, the value of `X` is `0`.

Given an array of strings `operations` containing a list of operations, return _the **final** value of_ `X` _after performing all the operations_.

**Example 1:**

**Input:** operations = ["--X","X++","X++"]
**Output:** 1
**Explanation:** The operations are performed as follows:
Initially, X = 0.
--X: X is decremented by 1, X =  0 - 1 = -1.
X++: X is incremented by 1, X = -1 + 1 =  0.
X++: X is incremented by 1, X =  0 + 1 =  1.

**Example 2:**

**Input:** operations = ["++X","++X","X++"]
**Output:** 3
**Explanation:** The operations are performed as follows:
Initially, X = 0.
++X: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
X++: X is incremented by 1, X = 2 + 1 = 3.

**Example 3:**

**Input:** operations = ["X++","++X","--X","X--"]
**Output:** 0
**Explanation:** The operations are performed as follows:
Initially, X = 0.
X++: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
--X: X is decremented by 1, X = 2 - 1 = 1.
X--: X is decremented by 1, X = 1 - 1 = 0.

**Constraints:**

* `1 <= operations.length <= 100`
* `operations[i]` will be either `"++X"`, `"X++"`, `"--X"`, or `"X--"`.

# Approaches
## Iteration with Full String Comparison
This is a straightforward approach where we iterate through the array of operations. For each operation, we use full string comparison to determine whether to increment or decrement the variable `X`.
**Time:** O(N), where N is the number of operations. We iterate through the array once. Although string comparison takes time proportional to the string length, the length is constant (3) in this problem, making each comparison an O(1) operation. · **Space:** O(1), as we only use a single integer variable to store the current value of X, requiring constant extra space regardless of the input size.
**Pros:** Easy to understand and implement.; Directly follows the problem statement, making the logic clear.
**Cons:** Slightly less performant in practice compared to checking a single character due to the overhead of `String.equals()` method calls which compare all characters in the string.
### Explanation
The core idea is to simulate the process described in the problem. We start with a variable `X` initialized to 0 and process each operation one by one. We use `if-else` conditions or a `switch` statement to match the operation string and update `X` accordingly.

Here is a code snippet demonstrating this approach:
```java
class Solution {
    public int finalValueAfterOperations(String[] operations) {
        int x = 0;
        for (String op : operations) {
            if (op.equals("++X") || op.equals("X++")) {
                x++;
            } else {
                x--;
            }
        }
        return x;
    }
}
```
A `switch` statement can also be used for clarity:
```java
class Solution {
    public int finalValueAfterOperations(String[] operations) {
        int x = 0;
        for (String op : operations) {
            switch (op) {
                case "++X":
                case "X++":
                    x++;
                    break;
                case "--X":
                case "X--":
                    x--;
                    break;
            }
        }
        return x;
    }
}
```
### Algorithm
*   Initialize an integer variable, `x`, to 0.
*   Iterate through the `operations` array from the first to the last element.
*   For each `operation` string:
    *   If the string is equal to `"++X"` or `"X++"`, increment `x` by 1.
    *   Otherwise, it must be a decrement operation (`"--X"` or `"X--"`), so decrement `x` by 1.
*   After the loop completes, return the final value of `x`.

## Optimized Iteration by Checking a Single Character
This approach improves upon the first one by leveraging a specific pattern in the operation strings. Instead of comparing the entire string, we can determine the operation type (increment or decrement) by checking just one specific character. This is more efficient as it avoids the overhead of full string comparisons.
**Time:** O(N), where N is the number of operations. We loop through the array once, and the work inside the loop (accessing a character at a specific index and comparing it) is a constant time O(1) operation. · **Space:** O(1). We only need a single integer variable to accumulate the result, so the space used is constant.
**Pros:** Most efficient solution in terms of practical performance due to minimal work per operation.; Code is simple and concise.; The logic is robust for the given problem constraints.
**Cons:** The logic is tied to the specific format of the operation strings. If the format changes (e.g., `"X = X + 1"`), the approach would need to be revised.
### Explanation
A closer look at the possible operation strings (`"++X"`, `"X++"`, `"--X"`, `"X--"`) reveals a useful pattern: the character at the middle index (index 1) is always `'+'` for increment operations and `'-'` for decrement operations. We can exploit this to simplify our logic.

This logic can be implemented concisely:
```java
class Solution {
    public int finalValueAfterOperations(String[] operations) {
        int x = 0;
        for (String op : operations) {
            if (op.charAt(1) == '+') {
                x++;
            } else {
                x--;
            }
        }
        return x;
    }
}
```
This can also be written elegantly using Java Streams, which performs the same underlying logic:
```java
import java.util.Arrays;

class Solution {
    public int finalValueAfterOperations(String[] operations) {
        return Arrays.stream(operations)
                     .mapToInt(op -> op.charAt(1) == '+' ? 1 : -1)
                     .sum();
    }
}
```
### Algorithm
*   Initialize an integer variable, `x`, to 0.
*   Iterate through the `operations` array.
*   For each `operation` string:
    *   Examine the character at index 1.
    *   If `operation.charAt(1)` is `'+'`, increment `x` by 1.
    *   If `operation.charAt(1)` is `'-'`, decrement `x` by 1.
*   After iterating through all operations, return the final value of `x`.

# Solutions
### Java

```java
class Solution {
public
  int finalValueAfterOperations(String[] operations) {
    int ans = 0;
    for (var s : operations) {
      ans += (s.charAt(1) == '+' ? 1 : -1);
    }
    return ans;
  }
}

```

### JavaScript

```javascript
/** * @param {string[]} operations * @return {number} */ var finalValueAfterOperations = function ( operations ) { let ans = 0 ; for ( const s of operations ) { ans += s [ 1 ] === ' + ' ? 1 : - 1 ; } return ans ; };
```

### Python

```python
class Solution:
    def finalValueAfterOperations(
        self, operations: List[str]) -> int: return sum(1 if s[1] == '+' else - 1 for s in operations)

```

### CPP

```cpp
class Solution {
public:
  int finalValueAfterOperations(vector<string> &operations) {
    int ans = 0;
    for (auto &s : operations)
      ans += (s[1] == '+' ? 1 : -1);
    return ans;
  }
};

```
