Final Value of Variable After Performing Operations
Apply a list of increment and decrement operations by reading a single distinguishing character
Problem Statement
You start with a variable X = 0 and are given an array of operation strings. Each string is one of:
| Operation | Effect |
|---|---|
"++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: 0Intuition
The four forms look like they need four cases, but two observations collapse them.
The key insight
-
Prefix vs. postfix is a red herring. In real C-like languages
++XandX++differ in what the expression evaluates to. Here the result is never used — only the final value ofXmatters — so both simply add1. -
Every string contains
Xand 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
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 xA 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 — stillO(1)per operation, but doing needless work.
Edge Cases
Related Problems
- Running Sum of 1d Array — accumulating across a single pass
- Evaluate Reverse Polish Notation — simulation where operand order genuinely does matter