Master Interview Like a Ninja

AI Interview Copilot and Assistant

Hey everyone, this is Alex, a software developer and interview prep enthusiast. In today’s blog, I’ll break down the ever-so-popular “Basic Calculator II” problem often tackled in coding interviews. If you’ve been perplexed by system design and algorithm-related interview prep, I promise to show you a step-by-step solution for implementing a calculator. Not to mention, if you’re new to stack-based operations or unsure why we need to consider operator precedence, you’ll leave here with clarity.

Before we dive in, let’s answer a quick question: Why do interviewers love asking this question?

The “Basic Calculator II” problem showcases your understanding of data structures, algorithmic efficiency, and parsing logic. Their end goal is to assess whether you can write code that handles edge cases, such as operator precedence, and is robust enough for real-world use.


What is “Basic Calculator II”?

Problem Statement: You need to implement a basic calculator to evaluate a given expression. The expression string contains:

  • Non-negative integers
  • Addition (+), subtraction (-), multiplication (*), and division (/) operators
  • Empty spaces (which you should ignore)
  • Ensure that integer division truncates towards zero (e.g., 5 / 2 gives 2).

Here’s a simple example:

Input: "3+2*2"
Output: 7

The rules? Perform multiplication and division first (operator precedence), then addition and subtraction (left-to-right associativity).

But here’s the twist: You must not use any built-in library functions for evaluation, like Python’s eval() or JavaScript's eval().

Generated Image


Why Use a Stack for This Problem?

To easily handle operator precedence without rewriting the order of operations, a stack proves to be a simple, effective choice. Here’s why:

  1. Handles Intermediate Results: By storing partial results, it enables us to delay adding or subtracting until higher-priority operations (like multiplication and division) are complete.
  2. Simple Pushing and Popping: Decisions like multiplying the top stack element can be done in O(1) time complexity.
  3. Space Efficiency: The size of the stack directly correlates to the number of operations processed.
To visualize: Expression Stack After Processing Comment
3 + 2 * 2 [3, 4] Multiplication done first (2 * 2)
4 * 3 - 5 [12, -5] Final addition (12 - 5) occurs last
5 / 2 [2] Integer division truncates decimals.

Step-by-Step Solution

1. Parsing Numbers and Operators

The first task when iterating over the string is to differentiate numbers from operators and spaces. Here’s why:

  • Numbers may span multiple digits (23, 45, etc.), and a while loop is used to create multi-digit numbers.
  • Operators (+, -, *, /) indicate the next calculation type.

Example:

  • Input string: "3+2*2"
  • Iteration outputs: 3 (push to stack), + (set sign to +), 2 (push to stack after operating), *, 2.

2. Implementing Multiplication and Division

To account for operator precedence, multiplication and division must immediately calculate a result before continuing to the next number.

  • Stack Top (Pop): Always pop the previous number stored.
  • Push Result Back: Multiply or divide and store the intermediate result on the stack.

Example:

  • Input: 2 * 2
  • Stack during process: [2] (pop for multiplication)[4 (push result)].

3. Handling Addition and Subtraction

Unlike the above, addition and subtraction wait until their operators appear to finish. Instead of computing immediately, they simply add the current number to the stack (with a positive or negative sign).

Final Step: Once all operators are processed, sum up the stack values for the final result.


Pseudocode for the Solution

This pseudocode will wrap up the above logic in a generalized way:

Initialize stack as empty
Initialize currentNum to 0, currentOp to '+'
Iterate over each character in the string
    If char is a digit:
        Append to currentNum to handle multi-digit numbers
    If char is an operator or end of string:
        If currentOp is '+', push currentNum
        If currentOp is '-', push -1 * currentNum
        If currentOp is '*', stack.pop() * currentNum → push result
        If currentOp is '/', int(stack.pop() / currentNum) → push result
        Update currentOp to char, reset currentNum to 0
Sum all the elements in the stack
Return the sum as the final result

Complete Java Implementation

Below is a complete, functional Java implementation of the solution.

class BasicCalculatorII {
    public int calculate(String s) {
        if (s == null || s.isEmpty()) return 0;

        Stack<Integer> stack = new Stack<>();
        int currNum = 0;
        char currOp = '+'; // Initialize the default operator as '+'

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            // Build the number if it's a digit
            if (Character.isDigit(c)) {
                currNum = currNum * 10 + (c - '0');
            }

            if (!Character.isDigit(c) && c != ' ' || i == s.length() - 1) {
                // Handle previous operator
                if (currOp == '+') stack.push(currNum);
                if (currOp == '-') stack.push(-currNum);
                if (currOp == '*') stack.push(stack.pop() * currNum);
                if (currOp == '/') stack.push(stack.pop() / currNum);

                // Update to the latest operator, reset currNum
                currOp = c;
                currNum = 0;
            }
        }

        // Sum up the stack
        int result = 0;
        for (int num : stack) result += num;

        return result;
    }
}

FAQ: Related Questions

Q1. Can I use a calculator in an aptitude test?

No, many tests specifically prohibit calculators to evaluate raw problem-solving skills. Mastering algorithms like this helps you excel in such tests!

Q2. How difficult is it to program a calculator?

Basic calculators are relatively simple, involving basic operations like addition and subtraction. However, incorporating operator precedence adds complexity.

Q3. Where can I practice system design interview questions?

Platforms like Ninjafy AI are invaluable for interview prep. Through mock interviews and AI feedback, they offer real-time scenarios to help you strengthen areas like system design.


Conclusion

While seemingly simple, the “Basic Calculator II” problem tests foundational coding skills. From implementing a stack to handling operator precedence, solving this problem reinforces key concepts in algorithm design. Alongside other coding challenges like finding the square root in Java or creating calculators in Python, it’s excellent training for technical interviews.

And don’t forget—interview excellence isn’t just about coding; it’s about confidence too! I personally use Ninjafy AI to simulate interviews. Its “mock interview” feature was a game-changer for me. Give it a shot if you’re serious about landing your next big role.

Happy coding, and see you in the next post!