Final Value of Variable After Performing Operations
Easy Simulation
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
A variable X starts at 0. You get a list of operations, each one of "++X", "X++", "--X" or "X--". Return X after applying all of them.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: start at 0, add 1 for every "++" and subtract 1 for every "--". The position of the ++ doesn't matter.
Why this works: the middle character of every operation is the sign, so one check per operation is enough. Constant work per item × n items = O(n).
Example: ["--X", "X++", "X++"]
"--X" → middle '-' → X = -1"X++" → middle '+' → X = 0"X++" → middle '+' → X = 1
✦Hints open one at a time
↗Approach
Loop once and look at character 1 of each operation. Constant work per operation gives O(n). It's a reminder that work done per element (here O(1)) multiplies with the loop size.
</>Solution (Java)
class Solution {
public int finalValueAfterOperations(String[] operations) {
int x = 0;
for (String op : operations) {
if (op.charAt(1) == '+') x++; // "++X" and "X++" both have '+' in the middle
else x--;
}
return x;
}
}
!Common mistake
Comparing strings with == in Java instead of equals(). Checking a single char avoids the issue entirely.
- Time: O(n).
- Space: O(1).

