Difficulty: 🟢 Easy
There is a programming language with only four operations and one variable X
:
++X
andX++
increments the value of the variableX
by1
.--X
andX--
decrements the value of the variableX
by1
.
Initially, the value of X
is 0
.
Given an array of strings operations
containing a list of operations, return
the final value of X
after performing all the operations.
Example 1:
Input: operations = ["--X","X++","X++"]
Output: 1
Explanation: The operations are performed as follows:
Initially, X = 0.
--X: X is decremented by 1, X = 0 - 1 = -1.
X++: X is incremented by 1, X = -1 + 1 = 0.
X++: X is incremented by 1, X = 0 + 1 = 1.
Example 2:
Input: operations = ["++X","++X","X++"]
Output: 3
Explanation: The operations are performed as follows:
Initially, X = 0.
++X: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
X++: X is incremented by 1, X = 2 + 1 = 3.
Example 3:
Input: operations = ["X++","++X","--X","X--"]
Output: 0
Explanation: The operations are performed as follows:
Initially, X = 0.
X++: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
--X: X is decremented by 1, X = 2 - 1 = 1.
X--: X is decremented by 1, X = 1 - 1 = 0.
1 <= operations.length <= 100
operations[i]
will be either"++X"
,"X++"
,"--X"
, or"X--"
.
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
total = 0
for operation in operations:
if operation == "--X" or operation == "X--":
total -= 1
else:
total += 1
return total
The given solution solves the problem by performing the following steps:
- Initialize a variable
total
to store the current value ofX
. - Iterate through each operation in the
operations
array. - For each operation, check its value:
- If the operation is
"--X"
or"X--"
, decrement the value oftotal
by 1. - Otherwise, increment the value of
total
by 1.
- If the operation is
- After performing all the operations, the final value of
X
is stored in thetotal
variable. - Return the value of
total
as the final answer.
The time complexity of this algorithm is O(n), where n is the length of the operations
array. This is because the algorithm performs a single pass through the array to evaluate each operation.
The space complexity of the algorithm is O(1) since it only uses a constant amount of memory to store the total
variable. The memory usage does not depend on the input size.
The given solution effectively evaluates the final value of X
after performing a series of operations. It iterates through the operations
array, incrementing or decrementing the total
variable based on the operation type. The algorithm has a time complexity of O(n) and a space complexity of O(1), making it an efficient solution for the problem.
NB: If you want to get community points please suggest solutions in other languages as merge requests.