On this page
Basic Calculator
Problem Highlights
- 🔗 Leetcode Link: https://leetcode.com/problems/basic-calculator/
- 💡 Problem Difficulty: Hard
- ⏰ Time to complete: 20 mins
- 🛠️ Topics: String
- 🗒️ Similar Questions: Evaluate Reverse Polish Notation, Basic Calculator II
1: U-nderstand
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
Be sure that you clarify the input and output parameters of the problem:
- Does space affect the evaluation of an input expression?
- Spaces do not affect the evaluation of the input expression
- Does the input contain valid strings?
- Input always contains valid strings
Run through a set of example cases:
HAPPY CASE
Example 1:
Input: s = "1 + 1"
Output: 2
Example 2:
Input: s = " 2-1 + 2 "
Output: 3
EDGE CASE
Example 3:
Input: s = "(1+(4+5+2)-3)+(6+8)"
Output: 23
2: M-atch
Match
For this string problem, we can think about the following techniques:
-
Sort If the given string is given in a proper order, the string can be sorted in a specified arrangement.
-
Two pointer solutions (left and right pointer variables) A two pointer solution would be used if you are searching pairs in a sorted array.
-
Storing the elements of the array in a HashMap or a Set A hashmap will allow us to store object and retrieve it in constant time, provided we know the key.
-
Traversing the array with a sliding window Using a sliding window is iterable and ordered and is normally used for a longest, shortest or optimal sequence that satisfies a given condition.
-
Stack A stack is the natural fit for nested expressions: when we reach a
(we save the running result and pending sign onto stacks, and when we reach a)we pop them back to combine with the inner result. None of the techniques above handle this nesting — the stack approach is what both implementations below use.
3: P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Whenever we see a (, put the intermediate result into the stack, and start new calculation right after this (. When we see a ), pop the add/minus the result with the last item in the stack.
1. Scan the expression from left to right, keeping a running result, the number currently being read, and the sign that applies to it.
2. When we read a digit, append it to the current number.
3. When we read + or -, add the current number to the running result with its pending sign, then reset the number and store the new sign.
4. When we read (, push the running result and the pending sign onto stacks, then start a fresh running result for the inner expression.
5. When we read ), finish the inner result, pop the saved sign (negating the inner result if it was -) and add the popped outer result.
6. After the loop, add any leftover number to the running result and return it.
⚠️ Common Mistakes
-
A tricky aspect of this problem includes handling a unary operator, such as “-3+3”, “4+(-5)”. Because the current number starts as “0”, a leading - just adds 0 to the running result and sets the pending sign, so no special case is needed.
-
Forgetting to save the pending sign along with the running result at each (. For example, consider 12-3+(4-(5+6)) traced through the code below:
- 12 is read, then - adds it: running result 12, pending sign -.
- 3 is read, then + subtracts it: running result 9, pending sign +.
- ( pushes 9 and +: nums_stack [9], ops_stack [+]. The running result resets to 0.
- 4 is read, then - adds it: running result 4, pending sign -.
- ( pushes 4 and -: nums_stack [9, 4], ops_stack [+, -]. The running result resets to 0.
- 5 is read, then + adds it: running result 5, pending sign +.
- 6 is read, then ) adds it to get the inner result 11. Popping 4 and - gives 4 - 11 = -7. Note that this is the same as if the input were 12-3+(4-11).
- ) adds the leftover 0, then pops 9 and + to give 9 + (-7) = 2.
- Nothing is left over after the loop, so the final result is 2.
4: I-mplement
Implement the code to solve the algorithm.
class Solution:
def calculate(self, s: str) -> int:
nums_stack = []
ops_stack =[]
cur_num = "0"
cur_op = "+"
running_result = 0
for i in range(len(s)):
c = s[i]
if c.isdigit():
cur_num += c
elif c in ["+", "-"]:
# before we replace cur_op, calculate previous num and put it into result
running_result += -1*int(cur_num) if cur_op == "-" else int(cur_num)
#refresh both
cur_num= "0"
cur_op = c
elif c == "(":
nums_stack.append(running_result)
ops_stack.append(cur_op)
running_result= 0
cur_op ="+"
cur_num = "0"
elif c == ")":
running_result += -1*int(cur_num) if cur_op == "-" else int(cur_num)
# take out previous context
prev_num = nums_stack.pop() if nums_stack else 0
prev_op = ops_stack.pop() if ops_stack else "+"
# update the new result
if prev_op =="-":
running_result = -1*running_result
running_result = prev_num + running_result
#refresh the context
cur_num= "0"
cur_op ="+"
#left over
if cur_num: running_result += -1*(int(cur_num)) if cur_op =="-" else int(cur_num)
return running_result
public class Solution {
public int calculate(String s) {
Stack<Integer> numsStack = new Stack<>();
Stack<Character> opsStack = new Stack<>();
String curNum = "0";
char curOp = '+';
int runningResult = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
curNum += c;
}
else if (c == '+' || c == '-') {
runningResult += (curOp == '-') ? -Integer.parseInt(curNum) : Integer.parseInt(curNum);
curNum = "0";
curOp = c;
}
else if (c == '(') {
numsStack.push(runningResult);
opsStack.push(curOp);
runningResult = 0;
curOp = '+';
curNum = "0";
}
else if (c == ')') {
runningResult += (curOp == '-') ? -Integer.parseInt(curNum) : Integer.parseInt(curNum);
int prevNum = (!numsStack.isEmpty()) ? numsStack.pop() : 0;
char prevOp = (!opsStack.isEmpty()) ? opsStack.pop() : '+';
if (prevOp == '-') {
runningResult = -runningResult;
}
runningResult = prevNum + runningResult;
curNum = "0";
curOp = '+';
}
}
if (!curNum.equals("")) {
runningResult += (curOp == '-') ? -Integer.parseInt(curNum) : Integer.parseInt(curNum);
}
return runningResult;
}
}
5: R-eview
Review the code by running specific example(s) and recording values (watchlist) of your code’s variables along the way.
- Trace through your code with an input to check for the expected output
- Catch possible edge cases and off-by-one errors
6: E-valuate
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
- Time Complexity: O(N), where N is the length of the string
- Space Complexity: O(N) to account for stack used