Final Value of Variable After Performing Operations — LeetCode 2011 Python Solution
- Problem
- #2011
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
There is a programming language with only four operations and one variable X: ++X and X++ increments the value of the variable X by 1. --X and X-- decrements the value of the variable X by 1.
Example
- Input
- operations = ["--X","X++","X++"]
- Output
- 1
- Explanation
- The operations are performed as follows:
Python solution
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
return sum(1 if s[1] == '+' else -1 for s in operations)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array \textit{operations} |
| Space | O(1) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2011. Final Value of Variable After Performing Operations is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2011. Final Value of Variable After Performing Operations?
- LeetCode 2011. Final Value of Variable After Performing Operations is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2011. Final Value of Variable After Performing Operations?
- The Python solution on this page runs in O(n), where n is the length of the array \textit{operations}.
- What is the space complexity of LeetCode 2011. Final Value of Variable After Performing Operations?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2011. Final Value of Variable After Performing Operations cover?
- LeetCode 2011. Final Value of Variable After Performing Operations is tagged Array, String and Simulation on LeetCode.