Back to posts

LeetCode Challenge Day 35 β€” 2011. Final Value of Variable After Performing Operations

Nitin Ahirwal / October 20, 2025

LeetCode ChallengeDay 35SimulationStringJavaScriptEasyPortfolio

Hey folks

This is Day 35 of my LeetCode streak πŸš€.
Today’s problem is 2011. Final Value of Variable After Performing Operations β€” a simple simulation problem where we execute increment/decrement operations and track the final result of a variable.


πŸ“Œ Problem Statement

You are given an array of strings operations, where each string is one of:

  • "--X", "X--" β†’ decrement by 1
  • "++X", "X++" β†’ increment by 1

Return the final value of variable X after performing all operations.


πŸ’‘ Intuition

The operations are straightforward β€” each one either increases or decreases X by 1.
We can simply simulate the process:

  • Start with X = 0.
  • For each operation, check if it contains "++" β†’ increment, else decrement.

πŸ”‘ Approach

  1. Initialize X = 0.
  2. Loop through all operations.
    • If the operation string contains "++", do X++.
    • Otherwise, do X--.
  3. Return the final value of X.

⏱️ Complexity Analysis

  • Time complexity:
    Each operation is processed in O(1). For n operations β†’ O(n).

  • Space complexity:
    Only a constant amount of memory is used β†’ O(1).


πŸ§‘β€πŸ’» Code (JavaScript)

/**
 * @param {string[]} operations
 * @return {number}
 */
var finalValueAfterOperations = function(operations) {
    let X = 0;
    for (let op of operations) {
        if (op.includes("++")) {
            X++;
        } else {
            X--;
        }
    }
    return X;
};

πŸ§ͺ Example Walkthrough

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

Start: X = 0

"--X" β†’ decrement β†’ X = -1

"X++" β†’ increment β†’ X = 0

"X++" β†’ increment β†’ X = 1

Output: 1

πŸŽ₯ Reflections

This problem is a nice reminder that not every LeetCode challenge needs advanced data structures or algorithms β€” sometimes a clean, simple simulation does the trick.

That’s it for Day 35 of my LeetCode journey! Onwards to the next challenge πŸ”₯

Happy Coding πŸ‘¨β€πŸ’»