Talentd
FleetCode
Make and follow sheets.Sign in

Final Value of Variable After Performing Operations solution and explanation

EasyArraySimulationString5 min read90.6% acceptanceUpdated 9 Apr 2026
Final Value of Variable After Performing Operations | LeetCode 2011 | EnglishCodeClips with Abhishek Ranjan · 4:34 · 2K viewsWatch on YouTube
9 more videos on this problem
  1. Final Value of Variable After Performing Operations | LeetCode 2011 | EnglishCodeClips with Abhishek Ranjan · 4:34 · 2K views
  2. 2011. Final Value of Variable After Performing Operations (Leetcode Easy)Programming Live with Larry · 2:36 · 1K views
  3. Leetcode | 2011. Final Value of Variable After Performing Operations | Easy | Java SolutionDeveloper Docs · 3:49 · 879 views
  4. 2011 Final Value of Variable After Performing Operations | JavaScript | devWithArsalan | LeetCodeArsalan Ahmed · 4:19 · 781 views
  5. 2011 Find value of a variable after performing operation | Leetcode - EasyThe Humble Coder · 5:34 · 473 views
  6. 2011. Final Value of Variable After Performing Operations | Leetcode Daily - PythonLeetcode Daily · 4:59 · 368 views
  7. LeetCode 2011 : Final Value of Variable After Performing Operations | Solution in JAVAAmit Manjarly · 3:40 · 285 views
  8. LeetCode 2011 | Final Value of Variable After Performing Operations | Char Check | JavaSleepy Cracker · 1:14 · 258 views
  9. Final Value of Variable After Performing Operations - Google Interview Questions - LeetCode SolutionnexTRIE · 2:30 · 226 views
  10. Final Value of Variable After Performing Operations | LeetCode 2011 - Pythonimpoldev · 4:06 · 221 views

The problem

There is a programming language with only four operations and one variable X:

  • ++X and X++ increments the value of the variable X by 1.
  • --X and X-- decrements the value of the variable X by 1.

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.

Constraints:

  • 1 <= operations.length <= 100
  • operations[i] will be either "++X", "X++", "--X", or "X--".

Approach overview

Problem Overview: You start with a variable X = 0. An array of strings contains operations such as ++X, X++, --X, and X--. Each increment operation increases X by 1 and each decrement operation decreases it by 1. The task is to process the list of operations and return the final value after all updates.

Approach 1: Iterative Count Approach (Time: O(n), Space: O(1))

Traverse the operations array once and update a counter that represents X. For every string, check whether it represents an increment or decrement. A simple check like if '+' in operation means the value increases; otherwise it decreases. This is a direct simulation of the operations and mirrors exactly what the problem statement describes. Since you only scan the array once and keep a single integer variable, the time complexity is O(n) and the space complexity is O(1). This approach works in any language and is the most straightforward solution.

Approach 2: Using String Count Method (Time: O(n), Space: O(1))

Instead of updating the variable step-by-step, count how many increment and decrement operations exist. Each operation string always contains either '+' or '-'. By counting how many strings contain '+' and subtracting the number containing '-', you can compute the final result directly. Languages like Python and JavaScript allow concise implementations using string membership checks or array filtering. The algorithm still scans the list once, so the time complexity remains O(n) with O(1) additional space.

The problem mainly tests basic iteration over an array and simple string inspection. Conceptually, it is a small simulation task: apply each operation exactly as written and track the result.

Recommended for interviews: The iterative simulation approach is what interviewers typically expect. It demonstrates that you read the problem carefully and can translate the operations directly into code with O(n) time and constant space. The string-count variant is equally efficient but mostly a stylistic shortcut available in languages with convenient string operations.

Approach 1: Iterative Count Approach

This approach involves iterating over each operation in the given list and modifying the variable X based on the operation. We start with X initialized to 0, and for each operation, we either increment or decrement X accordingly.

def final_value_after_operations(operations):
    X = 0
    for operation in operations:
        if operation[1] == '+':
            X += 1
        else:
            X -= 1
    return X

operations = ["--X", "X++", "X++"]
result = final_value_after_operations(operations)
print(result)
public class Main {
    public static int finalValueAfterOperations(String[] operations) {
        int X = 0;
        for (String operation : operations) {
            if (operation.charAt(1) == '+') {
                X++;
            } else {
                X--;
            }
        }
        return X;
    }

    public static void main(String[] args) {
        String[] operations = {"--X", "X++", "X++"};
        int result = finalValueAfterOperations(operations);
        System.out.println(result);
    }
}
#include <vector>
#include <string>
#include <iostream>

int finalValueAfterOperations(std::vector<std::string>& operations) {
    int X = 0;
    for (const std::string& op : operations) {
        if (op[1] == '+') {
            ++X;
        } else {
            --X;
        }
    }
    return X;
}

int main() {
    std::vector<std::string> operations = {"--X", "X++", "X++"};
    int result = finalValueAfterOperations(operations);
    std::cout << result << std::endl;
    return 0;
}
function finalValueAfterOperations(operations) {
    let X = 0;
    for (let operation of operations) {
        if (operation[1] === '+') {
            X++;
        } else {
            X--;
        }
    }
    return X;
}

let operations = ["--X", "X++", "X++"];
let result = finalValueAfterOperations(operations);
console.log(result);
#include <stdio.h>

int finalValueAfterOperations(char **operations, int operationsSize) {
    int X = 0;
    for (int i = 0; i < operationsSize; ++i) {
        if (operations[i][1] == '+') {
            X++;
        } else {
            X--;
        }
    }
    return X;
}

int main() {
    char *operations[] = {"--X", "X++", "X++"};
    int result = finalValueAfterOperations(operations, 3);
    printf("%d\n", result);
    return 0;
}
using System;

public class Program {
    public static int FinalValueAfterOperations(string[] operations) {
        int X = 0;
        foreach (var operation in operations) {
            if (operation[1] == '+') {
                X++;
            } else {
                X--;
            }
        }
        return X;
    }

    public static void Main() {
        string[] operations = {"--X", "X++", "X++"};
        int result = FinalValueAfterOperations(operations);
        Console.WriteLine(result);
    }
}

This Python code defines a function that initializes X to 0 and then iterates through each operation. Depending on whether the operation includes a '+', it increments or decrements X. The final result is returned.

Complexity

Time Complexity: O(n), where n is the number of operations.
Space Complexity: O(1), since the space usage is constant.

Try this approach in the editor

Approach 2: Using String Count Method

This approach counts the number of '+' and '-' operations directly. We count the times '++X' and 'X++' operations occur, and do the same for '--X' and 'X--'. The final value of X is calculated from the difference between the two counts.

def final_value_after_operations(operations):
    plus_count = operations.count('++X') + operations.count('X++')
    minus_count = operations.count('--X') + operations.count('X--')
    return plus_count - minus_count

operations = ["--X", "X++", "X++"]
result = final_value_after_operations(operations)
print(result)
function finalValueAfterOperations(operations) {
    let plusCount = operations.filter(op => op === '++X' || op === 'X++').length;
    let minusCount = operations.filter(op => op === '--X' || op === 'X--').length;
    return plusCount - minusCount;
}

let operations = ["--X", "X++", "X++"];
let result = finalValueAfterOperations(operations);
console.log(result);

This Python function uses the list's count method to calculate the number of increment and decrement operations separately. The final result is the difference between the counts of '+' and '-' operations.

Complexity

Time Complexity: O(n), where n is the number of operations.
Space Complexity: O(1), since the space is independent of input size.

Try this approach in the editor

Approach 3: Counting

We traverse the array operations. For each operation operations[i], if it contains '+', we increment the answer by 1, otherwise, we decrement the answer by 1.

The time complexity is O(n), where n is the length of the array operations. The space complexity is O(1).

function finalValueAfterOperations(operations: string[]): number {
    return operations.reduce((acc, op) => acc + (op[1] === '+' ? 1 : -1), 0);
}
func finalValueAfterOperations(operations []string) (ans int) {
	for _, s := range operations {
		if s[1] == '+' {
			ans += 1
		} else {
			ans -= 1
		}
	}
	return
}
impl Solution {
    pub fn final_value_after_operations(operations: Vec<String>) -> i32 {
        let mut ans = 0;
        for s in operations.iter() {
            ans += if s.as_bytes()[1] == b'+' { 1 } else { -1 };
        }
        ans
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Iterative Count Approach

Time Complexity: O(n), where n is the number of operations.
Space Complexity: O(1), since the space usage is constant.

Using String Count Method

Time Complexity: O(n), where n is the number of operations.
Space Complexity: O(1), since the space is independent of input size.

Counting–

Complexity analysis

ApproachTimeSpaceWhen to Use
Iterative Count (Simulation)O(n)O(1)Best general solution. Directly simulate each operation while scanning the array once.
String Count MethodO(n)O(1)Useful in Python/JavaScript for concise code using string membership or filtering.

Frequently asked questions

Is Final Value of Variable After Performing Operations easy or hard?

The problem is classified as Easy on LeetCode with a high acceptance rate. It mainly tests basic array traversal, string inspection, and simple simulation logic rather than advanced algorithms.

Final Value of Variable After Performing Operations Python/Java solution

In Python or Java, iterate through the operations list and check whether each string contains '+' or '-'. Increment the variable for '++X' or 'X++' and decrement it for '--X' or 'X--'. Both implementations run in O(n) time and O(1) space.

How to solve Final Value of Variable After Performing Operations in O(n)?

Initialize X = 0 and iterate through the operations array. If the current string contains '+', increment X; otherwise decrement X. After processing all elements, return X. This single-pass simulation ensures O(n) time and constant extra space.

What is the best approach for Final Value of Variable After Performing Operations?

The iterative simulation approach is the most common solution. Iterate through the operations array and increase or decrease a counter depending on whether the string contains '+' or '-'. This runs in O(n) time with O(1) space and directly models the operations described in the problem.

Is Final Value of Variable After Performing Operations asked at Google/Amazon/Meta?

This problem is categorized as an easy-level array and string simulation question. Variants of simple iteration and simulation problems appear frequently in interviews at large tech companies, especially during early screening rounds.

What data structure is used in Final Value of Variable After Performing Operations?

The problem primarily uses an array (or list) of strings to store operations. The algorithm only requires iterating over the array and updating an integer variable, so no additional complex data structures are needed.

What is the time complexity of Final Value of Variable After Performing Operations?

The optimal solution runs in O(n) time where n is the number of operations. Each operation string is processed exactly once. Only a single integer variable is maintained, so the space complexity is O(1).

Comments

Now write it yourselfClose this page and solve Final Value of Variable After Performing Operations in the editor, without looking.
Practise Final Value of Variable After Performing Operations