We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Final Value of Variable After Performing Operations

Number: 2137

Difficulty: Easy

Paid? No

Companies: Amazon, Meta


Problem Description

Calculate the final value of a variable X starting from 0 after performing a series of operations where "++X" and "X++" increment X by 1, and "--X" and "X--" decrement X by 1.


Key Insights

  • The operations are simple: both pre and post increment/decrement have the same effect.
  • Only one variable is affected, so we can simulate the operations directly.
  • The problem requires a linear scan through the operations list.

Space and Time Complexity

Time Complexity: O(n), where n is the number of operations.
Space Complexity: O(1), only a fixed number of variables are used.


Solution

The approach is to iterate over the list of operations and modify the variable X accordingly. For each operation, check if it contains a '+'; if it does, increment X by 1, otherwise decrement X by 1. This is a direct simulation with linear time complexity, and no additional data structures are needed apart from the loop variable.


Code Solutions

# Function to compute the final value of variable X after performing operations
def finalValueAfterOperations(operations):
    # Initialize X to 0
    x = 0
    # Process each operation in the list
    for op in operations:
        # If the operation contains '+', it is an increment
        if '+' in op:
            x += 1
        else:
            # Otherwise, it's a decrement
            x -= 1
    # Return the final value of X
    return x

# Example usage
if __name__ == "__main__":
    operations = ["--X", "X++", "X++"]
    print(finalValueAfterOperations(operations))  # Expected Output: 1
← Back to All Questions