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
Final Value of Variable After Operations INPUT operations array: ++X [0] ++X [1] --X [2] X++ [3] Initial Value X = 0 4 operations to process 2 increment, 1 decrement 1 more increment ALGORITHM STEPS 1 Check Character Look at ops[i][1] (middle character) 2 Detect '+' or '-' '+' means increment '-' means decrement 3 Update X Value X += 1 for '+' X -= 1 for '-' 4 Process All Ops Iterate through array Return final X Execution Trace ++X: char[1]='+' X=0+1=1 ++X: char[1]='+' X=1+1=2 --X: char[1]='-' X=2-1=1 X++: char[1]='+' X=1+1=2 FINAL RESULT Output 2 Calculation Summary Increments: 3 Decrements: 1 Final: 0 + 3 - 1 = 2 OK - Verified Time: O(n) Space: O(1) Key Insight: Character Detection Optimization Instead of comparing full strings like "++X" or "X++", we only check the middle character (index 1). The middle character is always '+' for increment and '-' for decrement. This works for all 4 operations! TutorialsPoint - Final Value of Variable After Performing Operations | Character Detection Approach
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