DSA Guide
Arrays

Final Value of Variable After Performing Operations

Apply a list of increment and decrement operations by reading a single distinguishing character

EasySimulation
ArrayStringSimulation
Problem #2011

Problem Statement

You start with a variable X = 0 and are given an array of operation strings. Each string is one of:

OperationEffect
"++X"increment, then read
"X++"read, then increment
"--X"decrement, then read
"X--"read, then decrement

Return the value of X after applying every operation in order.

Input:  operations = ["--X", "X++", "X++"]
Output: 1
Why:    0 → -1 → 0 → 1

Input:  operations = ["++X", "++X", "X++"]
Output: 3

Input:  operations = ["X++", "++X", "--X", "X--"]
Output: 0

Intuition

The four forms look like they need four cases, but two observations collapse them.

The key insight

  1. Prefix vs. postfix is a red herring. In real C-like languages ++X and X++ differ in what the expression evaluates to. Here the result is never used — only the final value of X matters — so both simply add 1.

  2. Every string contains X and two identical symbols. So one character is enough to identify the operation. operations[i][1] — the middle character — is + for both increment forms and - for both decrement forms.

"++X"     "X++"     "--X"     "X--"
  ↑         ↑         ↑         ↑
index 1   index 1   index 1   index 1
  '+'       '+'       '-'       '-'

The middle character is the single reliable discriminator: index 0 and index 2 vary between the forms, index 1 never does.

Approach

Watch it run

operations = ["--X", "X++", "X++"]
--X
X++
X++
X-1
Middle character is '-' → decrement. X goes from 0 to -1.
1 / 3

Solution

def final_value_after_operations(operations: list[str]) -> int:
    """Apply ++/-- operations to X, which starts at 0."""
    x = 0

    for op in operations:
        # op[1] is '+' for "++X" and "X++", '-' for "--X" and "X--".
        if op[1] == "+":
            x += 1
        else:
            x -= 1

    return x

A compact equivalent — each operation shifts X by +1 or -1:

def final_value_after_operations_short(operations: list[str]) -> int:
    return sum(1 if op[1] == "+" else -1 for op in operations)

Other characters that work

op.includes('+') and op[0] === '+' || op[2] === '+' are also correct. The middle character is preferred because it is a single fixed index with no scanning and no compound condition — the simplest thing that cannot be wrong.

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)

  • Time — one constant-time character test per operation.
  • Space — a single integer. Note that op.includes('+') would scan up to 3 characters instead of 1 — still O(1) per operation, but doing needless work.

Edge Cases

On this page