Final Value of Variable After Performing Operations - Problem
There is a programming language with only four operations and one variable X:
++XandX++increments the value of the variableXby 1.--XandX--decrements the value of the variableXby 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.
Input & Output
Example 1 — Mixed Operations
$
Input:
operations = ["++X","++X","--X","X++"]
›
Output:
2
💡 Note:
X starts at 0. ++X: X=1, ++X: X=2, --X: X=1, X++: X=2. Final value is 2.
Example 2 — Only Increments
$
Input:
operations = ["X++","++X"]
›
Output:
2
💡 Note:
X starts at 0. X++: X=1, ++X: X=2. Final value is 2.
Example 3 — Only Decrements
$
Input:
operations = ["--X","X--"]
›
Output:
-2
💡 Note:
X starts at 0. --X: X=-1, X--: X=-2. Final value is -2.
Constraints
- 1 ≤ operations.length ≤ 100
- operations[i] will be either "++X", "X++", "--X", or "X--".
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of operation strings
2
Process
Execute each operation on variable X
3
Output
Final value of X
Key Takeaway
🎯 Key Insight: All increment/decrement operations have the same effect regardless of pre/post notation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code