Final Value of Variable After Performing Operations
Problem
A tiny language has one integer variable X that starts at 0. Each operation is one of "++X", "X++", "--X", or "X--": the two + signs add 1 and the two - signs subtract 1, regardless of which side of X they sit on. Given the list of operations, return the final value of X after performing all of them in order.
operations = ["--X","X++","X++"]1operations = ["X++","++X","--X","X--"]0def final_value(operations):
x = 0
for op in operations:
if op[1] == "+":
x += 1
else:
x -= 1
return x
function finalValueAfterOperations(operations) {
let x = 0;
for (const op of operations) {
if (op[1] === "+") {
x += 1;
} else {
x -= 1;
}
}
return x;
}
int finalValueAfterOperations(String[] operations) {
int x = 0;
for (String op : operations) {
if (op.charAt(1) == '+') {
x += 1;
} else {
x -= 1;
}
}
return x;
}
int finalValueAfterOperations(vector<string>& operations) {
int x = 0;
for (string& op : operations) {
if (op[1] == '+') {
x += 1;
} else {
x -= 1;
}
}
return x;
}
Explanation
This is a small simulation: we keep a running value x starting at 0 and walk through the operations one by one, nudging x up or down for each.
The trick is realizing the position of X does not matter. "++X" and "X++" both add 1; "--X" and "X--" both subtract 1. So we never need to parse all three characters — we only need to know whether the operation increments or decrements.
Every valid operation has the same character at index 1: it is '+' for both increment forms and '-' for both decrement forms. So checking op[1] (the middle character) cleanly distinguishes the two cases with a single comparison.
If op[1] is '+' we do x += 1; otherwise we do x -= 1. After processing every operation we return x.
Example: ["--X","X++","X++"] walks 0 → −1 → 0 → 1, so the answer is 1. The loop runs once per operation with constant work each time.