#2011

Final Value of Variable After Performing Operations

Easy
ArrayStringSimulationSimulationCounting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of simulating each operation, we can count the number of increments and decrements directly. This allows us to compute the final value of X in a single pass.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize X to 0.
  2. 2Step 2: Loop through each operation in the operations array.
  3. 3Step 3: For each operation, if it is an increment, increase a counter; if it is a decrement, decrease a counter.
  4. 4Step 4: Return the final value of X as the difference between increments and decrements.
solution.py2 lines
1def finalValueAfterOperations(operations):
2    return sum(1 if op in ['++X', 'X++'] else -1 for op in operations)

Complexity note: The time complexity remains O(n) as we still iterate through the operations array once. The space complexity is O(1) because we only use a fixed amount of extra space for the count variable.

  • 1The operations can be categorized into increments and decrements, allowing for a more efficient counting approach.
  • 2The order of operations does not affect the final result, only the total counts of increments and decrements matter.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.