The Wayback Machine - https://web.archive.org/web/20240920160002/https://www.geeksforgeeks.org/expression-evaluation/
Open In App

Expression Evaluation

Last Updated : 21 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Medium
31.65%
850

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>


Output

22
212
1400
100

Time Complexity: O(n) 
Space Complexity: O(n)
See this for a sample run with more test cases.



Similar Reads

Arithmetic Expression Evaluation
The stack organization is very effective in evaluating arithmetic expressions. Expressions are usually represented in what is known as Infix notation, in which each operator is written between two operands (i.e., A + B). With this notation, we must distinguish between ( A + B )*C and A + ( B * C ) by using either parentheses or some operator-preced
2 min read
Evaluation of Postfix Expression
Given a postfix expression, the task is to evaluate the postfix expression. Postfix expression: The expression of the form "a b operator" (ab+) i.e., when a pair of operands is followed by an operator. Examples: Input: str = "2 3 1 * + 9 -"Output: -4Explanation: If the expression is converted into an infix expression, it will be 2 + (3 * 1) - 9 = 5
15+ min read
Evaluation of Expression Tree
Given a simple expression tree, consisting of basic binary operators i.e., + , - ,* and / and some integers, evaluate the expression tree. Examples: Input: Root node of the below tree Output:100 Input: Root node of the below tree Output: 110 Recommended PracticeExpression TreeTry It! Approach: The approach to solve this problem is based on followin
9 min read
Convert Infix expression to Postfix expression
Write a program to convert an Infix expression to Postfix form. Infix expression: The expression of the form "a operator b" (a + b) i.e., when an operator is in-between every pair of operands.Postfix expression: The expression of the form "a b operator" (ab+) i.e., When every pair of operands is followed by an operator. Examples: Input: A + B * C +
13 min read
Evaluation of Risk in Investments
Given two investment options A and B, we have to find the less risky investment of the two. The two investments A and B are each represented by an array. Each element in the array is a probable investment outcome. Thus each element in the array is a pair of two values. The first value is the amount of money received and the second value is the prob
12 min read
Remainder Evaluation
Given two positive integers Num1 and Num2, the task is to find the remainder when Num1 is divided by Num2. Examples: Input: Num1 = 11, Num2 = 3Output: 2Explanation: 3) 11 (3 - 9 --------- 2 -&gt; Remainder ---------- Input: Num1 = 15, Num2 = 3Output: 0 Approach 1: The problem can be solved by using the modulus operator. Modulus operator returns the
5 min read
Grid Evolution and Query Evaluation
Given a grid of dimensions n rows and m columns, where each element initially contains an integer from 0 to k-1. The grid evolves over time, with each element undergoing the transformation (grid[i][j] + 1) % k after each unit of time. You are also provided with a series of queries, each defined by [t, val, lx, ly, rx, ry], the task is to determine,
13 min read
Horner's Method for Polynomial Evaluation
Given a polynomial of the form cnxn + cn-1xn-1 + cn-2xn-2 + ... + c1x + c0 and a value of x, find the value of polynomial for a given value of x. Here cn, cn-1, .. are integers (may be negative) and n is a positive integer.Input is in the form of an array say poly[] where poly[0] represents coefficient for xn and poly[1] represents coefficient for
6 min read
Introduction to Evaluation Function of Minimax Algorithm in Game Theory
Prerequisite: Minimax Algorithm in Game TheoryAs seen in the above article, each leaf node had a value associated with it. We had stored this value in an array. But in the real world when we are creating a program to play Tic-Tac-Toe, Chess, Backgammon, etc. we need to implement a function that calculates the value of the board depending on the pla
8 min read
All ways to add parenthesis for evaluation
Given a string that represents an expression constituting numbers and binary operator +, - and * only. We need to parenthesize the expression in all possible way and return all evaluated values. Input : expr = “3-2-1”Output : {0, 2}((3-2)-1) = 0 (3-(2-1)) = 2Input : expr = "5*4-3*2"Output : {-10, 10, 14, 10, 34}(5*(4-(3*2))) = -10(5*((4-3)*2)) = 10
8 min read
Evaluation of Prefix Expressions
Prefix and Postfix expressions can be evaluated faster than an infix expression. This is because we don't need to process any brackets or follow operator precedence rule. In postfix and prefix expressions which ever operator comes before will be evaluated first, irrespective of its priority. Also, there are no brackets in these expressions. As long
13 min read
How to validate MAC address using Regular Expression
Given string str, the task is to check whether the given string is a valid MAC address or not by using Regular Expression. A valid MAC address must satisfy the following conditions: It must contain 12 hexadecimal digits.One way to represent them is to form six pairs of the characters separated with a hyphen (-) or colon(:). For example, 01-23-45-67
6 min read
How to validate Indian driving license number using Regular Expression
Given string str, the task is to check whether the given string is a valid Indian driving license number or not by using Regular Expression.The valid Indian driving license number must satisfy the following conditions: It should be 16 characters long (including space or hyphen (-)).The driving license number can be entered in any of the following f
7 min read
Identify and mark unmatched parenthesis in an expression
Given an expression, find and mark matched and unmatched parenthesis in it. We need to replace all balanced opening parenthesis with 0, balanced closing parenthesis with 1, and all unbalanced with -1.Examples: Input : ((a) Output : -10a1 Input : (a)) Output : 0a1-1 Input : (((abc))((d))))) Output : 000abc1100d111-1-1 The idea is based on a stack. W
6 min read
Map function and Lambda expression in Python to replace characters
Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input : str = 'grrksfoegrrks' c1 = e, c2 = r Output : geeksforgeeks Input : str = 'ratul' c1 = t, c2 = h Output : rahul We have an existing solution for this problem in C++. Please refer to Replace a character c1 with c2 and c2 with c1 in a string S. We can solve th
2 min read
Intersection of two arrays in Python ( Lambda expression and filter function )
Given two arrays, find their intersection. Examples: Input: arr1[] = [1, 3, 4, 5, 7] arr2[] = [2, 3, 5, 6] Output: Intersection : [3, 5] We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function. Implementation: C/C++ Code # Fun
1 min read
Expression contains redundant bracket or not
Given a string of balanced expressions, find if it contains a redundant parenthesis or not. A set of parenthesis is redundant if the same sub-expression is surrounded by unnecessary or multiple brackets. Print 'Yes' if redundant, else 'No'. Note: Expression may contain '+', '*', '-' and '/' operators. Given expression is valid and there are no whit
7 min read
Smallest expression to represent a number using single digit
Given a number N and a digit D, we have to form an expression or equation that contains only D and that expression evaluates to N. Allowed operators in an expression are +, -, *, and / . Find the minimum length expression that satisfies the condition above and D can only appear in the expression at most 10(limit) times. Hence limit the values of N
15+ min read
Maximum and Minimum Values of an Algebraic Expression
Given an algebraic expression of the form (x1 + x2 + x3 + . . . + xn) * (y1 + y2 + . . . + ym) and (n + m) integers. Find the maximum and minimum value of the expression using the given integers. Constraint : n &lt;= 50 m &lt;= 50 -50 &lt;= x1, x2, .. xn &lt;= 50 Examples : Input : n = 2, m = 2 arr[] = {1, 2, 3, 4} Output : Maximum : 25 Minimum : 2
14 min read
Balanced expression with replacement
Given a string that contains only the following =&gt; ‘{‘, ‘}’, ‘(‘, ‘)’, ‘[’, ‘]’. At some places there is ‘X’ in place of any bracket. Determine whether by replacing all ‘X’s with appropriate bracket, is it possible to make a valid bracket sequence. Prerequisite: Balanced Parenthesis Expression Examples: Input : S = "{(X[X])}" Output : Balanced T
13 min read
Check for balanced parentheses in an expression | O(1) space
Given a string of length n having parentheses in it, your task is to find whether given string has balanced parentheses or not. Please note there is constraint on space i.e. we are allowed to use only O(1) extra space. Also See : Check for balanced parentheses Examples: Input : (())[] Output : Yes Input : ))(({}{ Output : No If k = 1, then we will
15+ min read
Find the missing digit x from the given expression
Given an alphanumeric string, consisting of a single alphabet X, which represents an expression of the form: A operator B = C where A, B and C denotes integers and the operator can be either of +, -, * or / The task is to evaluate the missing digit X present in any of the integers A, B and C such that the given expression holds to be valid. Example
9 min read
Deriving the expression of Fibonacci Numbers in terms of golden ratio
Prerequisites: Generating Functions, Fibonacci Numbers, Methods to find Fibonacci numbers. The method of using Generating Functions to solve the famous and useful Fibonacci Numbers' recurrence has been discussed in this post. The Generating Function is a powerful tool for solving a wide variety of mathematical problems, including counting problems.
4 min read
How to validate CVV number using Regular Expression
Given string str, the task is to check whether it is a valid CVV (Card Verification Value) number or not by using Regular Expression. The valid CVV (Card Verification Value) number must satisfy the following conditions: It should have 3 or 4 digits.It should have a digit between 0-9.It should not have any alphabet or special characters. Examples: I
5 min read
Check if a String Contains Only Alphabets in Java Using Lambda Expression
Lambda expressions basically express instances of functional interfaces (An interface with a single abstract method is called functional interface. An example is java.lang.Runnable). lambda expressions implement the only abstract function and therefore implement functional interfaces. Given a String, we just need to iterate over characters again th
3 min read
Solve the Logical Expression given by string
Given string str representing a logical expression which consists of the operators | (OR), &amp; (AND),! (NOT) , 0, 1 and, only (i.e. no space between characters). The task is to print the result of the logical expression. Examples: Input: str = "[[0,&amp;,1],|,[!,1]]" Output: 0 Explanation:[[0,&amp;,1],|,[!,1]] [[0,&amp;,1],|,0] [[0,&amp;,1],|,0]
5 min read
Program to evaluate the expression (&radic;X+1)^6 + (&radic;X-1)^6
Given a number [Tex]X [/Tex]. The task is to find the value of the below expression for the given value of [Tex]X [/Tex]. [Tex](\sqrt[]{X} +1)^6 + (\sqrt[]{X}-1)^6[/Tex] Examples: Input: X = ?2 Output: 198 Explanation: [Tex]2[(\sqrt[]{2})^6 + 15 (\sqrt[]{2})^4 + 15\sqrt[]{2})^2 + 1] [/Tex]= 198Input: X = 3 Output: 4160 Approach: The idea is to use
3 min read
Find a permutation of 2N numbers such that the result of given expression is exactly 2K
Given two integers N and K, the task is to find a permutation of first 2*N natural numbers such that the following equation is satisfied. [Tex]\sum\limits_{i=1}^N |A_{2i-1}-A_{2i}| - |\sum\limits_{i=1}^N A_{2i-1}-A_{2i}|=2K [/Tex]Note: The value of K will always be less than or equal to N.Examples: Input : N = 1, K = 0 Output : 1 2 The result of th
5 min read
Print the balanced bracket expression using given brackets
Given four integers a, b, c and d which signifies the number of four types of brackets. "((""()"")(""))" The task is to print any balanced bracket expression using all the given brackets. If we cannot form a balanced bracket expression then print -1. In case of multiple answers, print any one. Examples: Input: a = 3, b = 1, c = 4, d = 3 Output: (((
6 min read
Maximize the value of the given expression
Given three non-zero integers a, b and c. The task is to find the maximum value possible by putting addition and multiplication signs between them in any order. Note: Rearrangement of integers is allowed but addition and multiplication sign must be used once. Braces can also be placed between equations as per your need. Examples: Input: a = 2, b =
8 min read
Article Tags :
Practice Tags :