algoadvance

Leetcode 2011. Final Value of Variable After Performing Operations

Problem Statement

Given an array of strings operations containing a list of operations on a variable X that start at 0, determine the final value of X after performing all the operations. Each operation is a string that can be one of the following: "--X", "X--", "++X", "X++".

Clarifying Questions

  1. What will be the maximum length of the operations array?
    • Typical size constraints apply, such as (1 \leq \text{operations.length} \leq 1000).
  2. Are the operation strings always valid strings as described?
    • Yes, all strings in the operations array will be one of the four valid operations.
  3. What should be the initial value of X?
    • The initial value of X is always 0.

Strategy

  1. Initialize a variable X to 0.
  2. Traverse through each string in the operations array.
  3. For each operation, update the value of X accordingly:
    • Increment X if the operation is "++X" or "X++".
    • Decrement X if the operation is "--X" or "X--".
  4. Return the final value of X after applying all operations.

Code

Here’s the implementation of the plan in C++:

#include <vector>
#include <string>

int finalValueAfterOperations(std::vector<std::string>& operations) {
    int X = 0;
    for (const std::string& operation : operations) {
        if (operation == "++X" || operation == "X++") {
            X++;
        } else if (operation == "--X" || operation == "X--") {
            X--;
        }
    }
    return X;
}

Explanation

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI