878742. Evaluate Formulae

Basic

Evaluate Formulae

Summary

Given a string representing a mathematical formula, evaluate it. The formula will consist of numbers and basic arithmetic operations (+, -, *, /). For example, "1 + 2 * 3" should return 7.

Detailed Explanation

To solve this problem, we can use the Shunting-yard algorithm, also known as the polish notation conversion algorithm. This algorithm is used to convert infix expressions into postfix expressions. Infix expressions are those where operators are placed between the operands (e.g., "1 + 2 * 3"), while postfix expressions are those where operators follow the operands (e.g., "1 2 3 + *").

Here's a step-by-step breakdown of the solution:

  1. Tokenize the input string into individual tokens, which can be numbers or operators.
  2. Convert the infix expression into postfix notation using the Shunting-yard algorithm.
  3. Evaluate the postfix expression by iterating through it and performing the operations in the correct order.

The time complexity of this solution is O(n), where n is the length of the input string, as we need to iterate through each character once. The space complexity is also O(n), as we may need to store all tokens in memory during the tokenization step.

Here's an ASCII art diagram illustrating the conversion from infix to postfix:

     1 + 2 * 3
    /   \
  +      *
 / \    / \
1 2 3  2 3

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.Stack;

public class FormulaEvaluator {
    public static int evaluate(String formula) {
        Stack<String> stack = new Stack<>();
        StringBuilder sb = new StringBuilder();

        for (char c : formula.toCharArray()) {
            if (Character.isDigit(c)) {
                sb.append(c);
            } else if (c == ' ') {
                // ignore spaces
            } else {
                String token = sb.toString();
                if (!token.isEmpty()) {
                    stack.push(token);
                    sb.setLength(0);
                }
                stack.push(String.valueOf(c));
            }
        }

        if (!sb.toString().isEmpty()) {
            stack.push(sb.toString());
        }

        int result = 0;
        Stack<String> opStack = new Stack<>();
        String prevOp = "";

        while (!stack.isEmpty()) {
            String token = stack.pop();
            if (token.matches("\\d+")) {
                int num = Integer.parseInt(token);
                if (prevOp.equals("+")) {
                    result += num;
                } else if (prevOp.equals("-")) {
                    result -= num;
                } else if (prevOp.equals("*")) {
                    result *= num;
                } else if (prevOp.equals("/")) {
                    result /= num;
                }
            } else {
                opStack.push(token);
                prevOp = token;
            }
        }

        return result;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.