Evaluate an expression represented by a String. The expression can contain parentheses, you can assume parentheses are well-matched. For simplicity, you can assume only binary operations allowed are +, -, *, and /. Arithmetic Expressions can be written in one of three forms:
- Infix Notation: Operators are written between the operands they operate on, e.g. 3 + 4.
- Prefix Notation: Operators are written before the operands, e.g + 3 4
- Postfix Notation: Operators are written after operands.
Infix Expressions are harder for Computers to evaluate because of the additional work needed to decide precedence. Infix notation is how expressions are written and recognized by humans and, generally, input to programs. Given that they are harder to evaluate, they are generally converted to one of the two remaining forms. A very well known algorithm for converting an infix notation to a postfix notation is Shunting Yard Algorithm by Edgar Dijkstra.
This algorithm takes as input an Infix Expression and produces a queue that has this expression converted to postfix notation. The same algorithm can be modified so that it outputs the result of the evaluation of expression instead of a queue. The trick is using two stacks instead of one, one for operands, and one for operators.
1. While there are still tokens to be read in,
1.1 Get the next token.
1.2 If the token is:
1.2.1 A number: push it onto the value stack.
1.2.2 A variable: get its value, and push onto the value stack.
1.2.3 A left parenthesis: push it onto the operator stack.
1.2.4 A right parenthesis:
1 While the thing on top of the operator stack is not a
left parenthesis,
1 Pop the operator from the operator stack.
2 Pop the value stack twice, getting two operands.
3 Apply the operator to the operands, in the correct order.
4 Push the result onto the value stack.
2 Pop the left parenthesis from the operator stack, and discard it.
1.2.5 An operator (call it thisOp):
1 While the operator stack is not empty, and the top thing on the
operator stack has the same or greater precedence as thisOp,
1 Pop the operator from the operator stack.
2 Pop the value stack twice, getting two operands.
3 Apply the operator to the operands, in the correct order.
4 Push the result onto the value stack.
2 Push thisOp onto the operator stack.
2. While the operator stack is not empty,
1 Pop the operator from the operator stack.
2 Pop the value stack twice, getting two operands.
3 Apply the operator to the operands, in the correct order.
4 Push the result onto the value stack.
3. At this point the operator stack should be empty, and the value
stack should have only one value in it, which is the final result.
Implementation: It should be clear that this algorithm runs in linear time - each number or operator is pushed onto and popped from Stack only once.
C++
// CPP program to evaluate a given
// expression where tokens are
// separated by space.
#include <bits/stdc++.h>
using namespace std;
// Function to find precedence of
// operators.
int precedence(char op){
if(op == '+'||op == '-')
return 1;
if(op == '*'||op == '/')
return 2;
return 0;
}
// Function to perform arithmetic operations.
int applyOp(int a, int b, char op){
switch(op){
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
}
// Function that returns value of
// expression after evaluation.
int evaluate(string tokens){
int i;
// stack to store integer values.
stack <int> values;
// stack to store operators.
stack <char> ops;
for(i = 0; i < tokens.length(); i++){
// Current token is a whitespace,
// skip it.
if(tokens[i] == ' ')
continue;
// Current token is an opening
// brace, push it to 'ops'
else if(tokens[i] == '('){
ops.push(tokens[i]);
}
// Current token is a number, push
// it to stack for numbers.
else if(isdigit(tokens[i])){
int val = 0;
// There may be more than one
// digits in number.
while(i < tokens.length() &&
isdigit(tokens[i]))
{
val = (val*10) + (tokens[i]-'0');
i++;
}
values.push(val);
// right now the i points to
// the character next to the digit,
// since the for loop also increases
// the i, we would skip one
// token position; we need to
// decrease the value of i by 1 to
// correct the offset.
i--;
}
// Closing brace encountered, solve
// entire brace.
else if(tokens[i] == ')')
{
while(!ops.empty() && ops.top() != '(')
{
int val2 = values.top();
values.pop();
int val1 = values.top();
values.pop();
char op = ops.top();
ops.pop();
values.push(applyOp(val1, val2, op));
}
// pop opening brace.
if(!ops.empty())
ops.pop();
}
// Current token is an operator.
else
{
// While top of 'ops' has same or greater
// precedence to current token, which
// is an operator. Apply operator on top
// of 'ops' to top two elements in values stack.
while(!ops.empty() && precedence(ops.top())
>= precedence(tokens[i])){
int val2 = values.top();
values.pop();
int val1 = values.top();
values.pop();
char op = ops.top();
ops.pop();
values.push(applyOp(val1, val2, op));
}
// Push current token to 'ops'.
ops.push(tokens[i]);
}
}
// Entire expression has been parsed at this
// point, apply remaining ops to remaining
// values.
while(!ops.empty()){
int val2 = values.top();
values.pop();
int val1 = values.top();
values.pop();
char op = ops.top();
ops.pop();
values.push(applyOp(val1, val2, op));
}
// Top of 'values' contains result, return it.
return values.top();
}
int main() {
cout << evaluate("10 + 2 * 6") << "\n";
cout << evaluate("100 * 2 + 12") << "\n";
cout << evaluate("100 * ( 2 + 12 )") << "\n";
cout << evaluate("100 * ( 2 + 12 ) / 14");
return 0;
}
// This code is contributed by Nikhil jindal.
Java
/* A Java program to evaluate a
given expression where tokens
are separated by space.
*/
import java.util.Stack;
public class EvaluateString
{
public static int evaluate(String expression)
{
char[] tokens = expression.toCharArray();
// Stack for numbers: 'values'
Stack<Integer> values = new
Stack<Integer>();
// Stack for Operators: 'ops'
Stack<Character> ops = new
Stack<Character>();
for (int i = 0; i < tokens.length; i++)
{
// Current token is a
// whitespace, skip it
if (tokens[i] == ' ')
continue;
// Current token is a number,
// push it to stack for numbers
if (tokens[i] >= '0' &&
tokens[i] <= '9')
{
StringBuffer sbuf = new
StringBuffer();
// There may be more than one
// digits in number
while (i < tokens.length &&
tokens[i] >= '0' &&
tokens[i] <= '9')
sbuf.append(tokens[i++]);
values.push(Integer.parseInt(sbuf.
toString()));
// right now the i points to
// the character next to the digit,
// since the for loop also increases
// the i, we would skip one
// token position; we need to
// decrease the value of i by 1 to
// correct the offset.
i--;
}
// Current token is an opening brace,
// push it to 'ops'
else if (tokens[i] == '(')
ops.push(tokens[i]);
// Closing brace encountered,
// solve entire brace
else if (tokens[i] == ')')
{
while (ops.peek() != '(')
values.push(applyOp(ops.pop(),
values.pop(),
values.pop()));
ops.pop();
}
// Current token is an operator.
else if (tokens[i] == '+' ||
tokens[i] == '-' ||
tokens[i] == '*' ||
tokens[i] == '/')
{
// While top of 'ops' has same
// or greater precedence to current
// token, which is an operator.
// Apply operator on top of 'ops'
// to top two elements in values stack
while (!ops.empty() &&
hasPrecedence(tokens[i],
ops.peek()))
values.push(applyOp(ops.pop(),
values.pop(),
values.pop()));
// Push current token to 'ops'.
ops.push(tokens[i]);
}
}
// Entire expression has been
// parsed at this point, apply remaining
// ops to remaining values
while (!ops.empty())
values.push(applyOp(ops.pop(),
values.pop(),
values.pop()));
// Top of 'values' contains
// result, return it
return values.pop();
}
// Returns true if 'op2' has higher
// or same precedence as 'op1',
// otherwise returns false.
public static boolean hasPrecedence(
char op1, char op2)
{
if (op2 == '(' || op2 == ')')
return false;
if ((op1 == '*' || op1 == '/') &&
(op2 == '+' || op2 == '-'))
return false;
else
return true;
}
// A utility method to apply an
// operator 'op' on operands 'a'
// and 'b'. Return the result.
public static int applyOp(char op,
int b, int a)
{
switch (op)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw new
UnsupportedOperationException(
"Cannot divide by zero");
return a / b;
}
return 0;
}
// Driver method to test above methods
public static void main(String[] args)
{
System.out.println(EvaluateString.
evaluate("10 + 2 * 6"));
System.out.println(EvaluateString.
evaluate("100 * 2 + 12"));
System.out.println(EvaluateString.
evaluate("100 * ( 2 + 12 )"));
System.out.println(EvaluateString.
evaluate("100 * ( 2 + 12 ) / 14"));
}
}
Python3
# Python3 program to evaluate a given
# expression where tokens are
# separated by space.
# Function to find precedence
# of operators.
def precedence(op):
if op == '+' or op == '-':
return 1
if op == '*' or op == '/':
return 2
return 0
# Function to perform arithmetic
# operations.
def applyOp(a, b, op):
if op == '+': return a + b
if op == '-': return a - b
if op == '*': return a * b
if op == '/': return a // b
# Function that returns value of
# expression after evaluation.
def evaluate(tokens):
# stack to store integer values.
values = []
# stack to store operators.
ops = []
i = 0
while i < len(tokens):
# Current token is a whitespace,
# skip it.
if tokens[i] == ' ':
i += 1
continue
# Current token is an opening
# brace, push it to 'ops'
elif tokens[i] == '(':
ops.append(tokens[i])
# Current token is a number, push
# it to stack for numbers.
elif tokens[i].isdigit():
val = 0
# There may be more than one
# digits in the number.
while (i < len(tokens) and
tokens[i].isdigit()):
val = (val * 10) + int(tokens[i])
i += 1
values.append(val)
# right now the i points to
# the character next to the digit,
# since the for loop also increases
# the i, we would skip one
# token position; we need to
# decrease the value of i by 1 to
# correct the offset.
i-=1
# Closing brace encountered,
# solve entire brace.
elif tokens[i] == ')':
while len(ops) != 0 and ops[-1] != '(':
val2 = values.pop()
val1 = values.pop()
op = ops.pop()
values.append(applyOp(val1, val2, op))
# pop opening brace.
ops.pop()
# Current token is an operator.
else:
# While top of 'ops' has same or
# greater precedence to current
# token, which is an operator.
# Apply operator on top of 'ops'
# to top two elements in values stack.
while (len(ops) != 0 and
precedence(ops[-1]) >=
precedence(tokens[i])):
val2 = values.pop()
val1 = values.pop()
op = ops.pop()
values.append(applyOp(val1, val2, op))
# Push current token to 'ops'.
ops.append(tokens[i])
i += 1
# Entire expression has been parsed
# at this point, apply remaining ops
# to remaining values.
while len(ops) != 0:
val2 = values.pop()
val1 = values.pop()
op = ops.pop()
values.append(applyOp(val1, val2, op))
# Top of 'values' contains result,
# return it.
return values[-1]
# Driver Code
if __name__ == "__main__":
print(evaluate("10 + 2 * 6"))
print(evaluate("100 * 2 + 12"))
print(evaluate("100 * ( 2 + 12 )"))
print(evaluate("100 * ( 2 + 12 ) / 14"))
# This code is contributed
# by Rituraj Jain
C#
/* A C# program to evaluate a given
expression where tokens
are separated by space.
*/
using System;
using System.Collections.Generic;
using System.Text;
public class EvaluateString
{
public static int evaluate(string expression)
{
char[] tokens = expression.ToCharArray();
// Stack for numbers: 'values'
Stack<int> values = new Stack<int>();
// Stack for Operators: 'ops'
Stack<char> ops = new Stack<char>();
for (int i = 0; i < tokens.Length; i++)
{
// Current token is a whitespace, skip it
if (tokens[i] == ' ')
{
continue;
}
// Current token is a number,
// push it to stack for numbers
if (tokens[i] >= '0' && tokens[i] <= '9')
{
StringBuilder sbuf = new StringBuilder();
// There may be more than
// one digits in number
while (i < tokens.Length &&
tokens[i] >= '0' &&
tokens[i] <= '9')
{
sbuf.Append(tokens[i++]);
}
values.Push(int.Parse(sbuf.ToString()));
// Right now the i points to
// the character next to the digit,
// since the for loop also increases
// the i, we would skip one
// token position; we need to
// decrease the value of i by 1 to
// correct the offset.
i--;
}
// Current token is an opening
// brace, push it to 'ops'
else if (tokens[i] == '(')
{
ops.Push(tokens[i]);
}
// Closing brace encountered,
// solve entire brace
else if (tokens[i] == ')')
{
while (ops.Peek() != '(')
{
values.Push(applyOp(ops.Pop(),
values.Pop(),
values.Pop()));
}
ops.Pop();
}
// Current token is an operator.
else if (tokens[i] == '+' ||
tokens[i] == '-' ||
tokens[i] == '*' ||
tokens[i] == '/')
{
// While top of 'ops' has same
// or greater precedence to current
// token, which is an operator.
// Apply operator on top of 'ops'
// to top two elements in values stack
while (ops.Count > 0 &&
hasPrecedence(tokens[i],
ops.Peek()))
{
values.Push(applyOp(ops.Pop(),
values.Pop(),
values.Pop()));
}
// Push current token to 'ops'.
ops.Push(tokens[i]);
}
}
// Entire expression has been
// parsed at this point, apply remaining
// ops to remaining values
while (ops.Count > 0)
{
values.Push(applyOp(ops.Pop(),
values.Pop(),
values.Pop()));
}
// Top of 'values' contains
// result, return it
return values.Pop();
}
// Returns true if 'op2' has
// higher or same precedence as 'op1',
// otherwise returns false.
public static bool hasPrecedence(char op1,
char op2)
{
if (op2 == '(' || op2 == ')')
{
return false;
}
if ((op1 == '*' || op1 == '/') &&
(op2 == '+' || op2 == '-'))
{
return false;
}
else
{
return true;
}
}
// A utility method to apply an
// operator 'op' on operands 'a'
// and 'b'. Return the result.
public static int applyOp(char op,
int b, int a)
{
switch (op)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
{
throw new
System.NotSupportedException(
"Cannot divide by zero");
}
return a / b;
}
return 0;
}
// Driver method to test above methods
public static void Main(string[] args)
{
Console.WriteLine(EvaluateString.
evaluate("10 + 2 * 6"));
Console.WriteLine(EvaluateString.
evaluate("100 * 2 + 12"));
Console.WriteLine(EvaluateString.
evaluate("100 * ( 2 + 12 )"));
Console.WriteLine(EvaluateString.
evaluate("100 * ( 2 + 12 ) / 14"));
}
}
// This code is contributed by Shrikant13
JavaScript
<script>
/* A Javascript program to evaluate a given
expression where tokens
are separated by space.
*/
function evaluate(expression)
{
let tokens = expression.split('');
// Stack for numbers: 'values'
let values = [];
// Stack for Operators: 'ops'
let ops = [];
for (let i = 0; i < tokens.length; i++)
{
// Current token is a whitespace, skip it
if (tokens[i] == ' ')
{
continue;
}
// Current token is a number,
// push it to stack for numbers
if (tokens[i] >= '0' && tokens[i] <= '9')
{
let sbuf = "";
// There may be more than
// one digits in number
while (i < tokens.length &&
tokens[i] >= '0' &&
tokens[i] <= '9')
{
sbuf = sbuf + tokens[i++];
}
values.push(parseInt(sbuf, 10));
// Right now the i points to
// the character next to the digit,
// since the for loop also increases
// the i, we would skip one
// token position; we need to
// decrease the value of i by 1 to
// correct the offset.
i--;
}
// Current token is an opening
// brace, push it to 'ops'
else if (tokens[i] == '(')
{
ops.push(tokens[i]);
}
// Closing brace encountered,
// solve entire brace
else if (tokens[i] == ')')
{
while (ops[ops.length - 1] != '(')
{
values.push(applyOp(ops.pop(),
values.pop(),
values.pop()));
}
ops.pop();
}
// Current token is an operator.
else if (tokens[i] == '+' ||
tokens[i] == '-' ||
tokens[i] == '*' ||
tokens[i] == '/')
{
// While top of 'ops' has same
// or greater precedence to current
// token, which is an operator.
// Apply operator on top of 'ops'
// to top two elements in values stack
while (ops.length > 0 &&
hasPrecedence(tokens[i],
ops[ops.length - 1]))
{
values.push(applyOp(ops.pop(),
values.pop(),
values.pop()));
}
// Push current token to 'ops'.
ops.push(tokens[i]);
}
}
// Entire expression has been
// parsed at this point, apply remaining
// ops to remaining values
while (ops.length > 0)
{
values.push(applyOp(ops.pop(),
values.pop(),
values.pop()));
}
// Top of 'values' contains
// result, return it
return values.pop();
}
// Returns true if 'op2' has
// higher or same precedence as 'op1',
// otherwise returns false.
function hasPrecedence(op1, op2)
{
if (op2 == '(' || op2 == ')')
{
return false;
}
if ((op1 == '*' || op1 == '/') &&
(op2 == '+' || op2 == '-'))
{
return false;
}
else
{
return true;
}
}
// A utility method to apply an
// operator 'op' on operands 'a'
// and 'b'. Return the result.
function applyOp(op, b, a)
{
switch (op)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
{
document.write("Cannot divide by zero");
}
return parseInt(a / b, 10);
}
return 0;
}
document.write(evaluate("10 + 2 * 6") + "</br>");
document.write(evaluate("100 * 2 + 12") + "</br>");
document.write(evaluate("100 * ( 2 + 12 )") + "</br>");
document.write(evaluate("100 * ( 2 + 12 ) / 14") + "</br>");
// This code is contributed by decode2207.
</script>
Time Complexity: O(n)
Space Complexity: O(n)
See this for a sample run with more test cases.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem