#2011

Final Value of Variable After Performing Operations

Easy Simulation

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. 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

</>Solution (Java)

!Common mistake

Comparing strings with == in Java instead of equals(). Checking a single char avoids the issue entirely.