Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Both increment spellings increase the variable by one, and both decrement spellings decrease it by one. Their prefix or postfix placement does not affect the final value because no intermediate expression result is used.
Approach
Start the variable at zero. For each guaranteed-valid operation, add one if it contains +; otherwise subtract one. Return the resulting value after every operation. The strings have fixed length, so inspecting their sign is constant work, and there is no need to parse or execute the strings as code.
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x = 0
for o in operations:
if '+' in o:
x += 1
else:
x -= 1
return xComplexity analysis
Let n = operations.length. Time: O(n). Auxiliary space: O(1).
