Leetcode 2011. Final Value of Variable After Performing Operations
You are given an integer variable x
initialized to 0
. You are also given a string array operations
where operations[i]
is one of "++X"
, "X++"
, "--X"
, and "X--"
. You need to perform the operations on x
and return the final value of x
.
"++X"
and "X++"
both increment the value of x
by 1
."--X"
and "X--"
both decrement the value of x
by 1
.Q: Are there any constraints on the length of the operations
array?
A: The length of the operations
array will be within the range 1 to 100.
Q: Are there any other types of operations except the four specified?
A: No, the operations will strictly be one of "++X"
, "X++"
, "--X"
, and "X--"
.
Q: Can the operations array contain duplicate operations? A: Yes, the array can contain duplicates of the specified operations.
x
to 0
.operations
array.x
if the operation is "++X"
or "X++"
.x
if the operation is "--X"
or "X--"
.x
after processing all operations.public class Solution {
public int finalValueAfterOperations(String[] operations) {
int x = 0;
for (String operation : operations) {
if (operation.equals("++X") || operation.equals("X++")) {
x++;
} else if (operation.equals("--X") || operation.equals("X--")) {
x--;
}
}
return x;
}
public static void main(String[] args) {
Solution solution = new Solution();
String[] operations = {"++X", "X++", "--X", "--X"};
System.out.println(solution.finalValueAfterOperations(operations)); // Output should be 0
}
}
The time complexity of this solution is O(n), where n
is the length of the operations
array. This is because we are iterating through the array once and performing constant time operations for each element.
The space complexity is O(1), as we are only using a fixed amount of extra space regardless of the input size (int x
).
This solution efficiently handles the problem within the provided constraints and ensures correct results by properly processing each element in the operations
array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?