Final Value of Variable After Performing Operations - 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.

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
Variable Operations: Transform X from 0 to Final ValueX = 0 (initial)"++X""++X""--X""X++"X: 0→1X: 1→2X: 2→1X: 1→2Final Result: X = 2Process: 3 increments (+3) and 1 decrement (-1) = +2
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
Asked in
Amazon 15 Microsoft 12 Google 8 Facebook 5
82.6K Views
High Frequency
~5 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen