Final Value of Variable After Performing Operations

Here’s a simple solution using a counter variable:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from typing import List

class Solution:
    def finalValueAfterOperations(self, operations: List[str]) -> int:
        X = 0  # start with X as 0
        for operation in operations:
            if operation in ["++X", "X++"]:
                X += 1  # increment X by 1
            else:
                X -= 1  # decrement X by 1
        return X

This code loops through the given operations. If the operation is an increment operation ("++X" or “X++”), we increment our counter X by 1. If the operation is a decrement operation ("–X" or “X–”), we decrement X by 1. Finally, we return the value of X.

This code treats “++X” and “X++” as the same operation, and “–X” and “X–” as the same operation. This is because in Python and many other languages, there’s no difference between pre-increment/post-increment or pre-decrement/post-decrement. The exact behavior can depend on the language, but for this problem, we assume they have the same effect.