The Wayback Machine - https://web.archive.org/web/20240818161254/https://www.geeksforgeeks.org/evaluation-prefix-expressions/
Open In App

Evaluation of Prefix Expressions

Last Updated : 26 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 as we can guarantee that a valid prefix or postfix expression is used, it can be evaluated with correctness.

We can convert infix to postfix and can convert infix to prefix.
In this article, we will discuss how to evaluate an expression written in prefix notation. The method is similar to evaluating a postfix expression. Please read Evaluation of Postfix Expression to know how to evaluate postfix expressions

Algorithm:

EVALUATE_PREFIX(STRING)
Step 1: Put a pointer P at the end of the string
Step 2: If character at P is an operand push it to Stack
Step 3: If the character at P is an operator pop two
elements from the Stack. Operate on these elements
according to the operator, and push the result
back to the Stack
Step 4: Decrement P by 1 and go to Step 2 as long as there
are characters left to be scanned in the expression.
Step 5: The Result is stored at the top of the Stack,
return it
Step 6: End

Example to demonstrate working of the algorithm  

Expression: +9*26

Character | Stack | Explanation
Scanned | (Front to |
| Back) |
-------------------------------------------
6 6 6 is an operand,
push to Stack
2 6 2 2 is an operand,
push to Stack
* 12 (6*2) * is an operator,
pop 6 and 2, multiply
them and push result
to Stack
9 12 9 9 is an operand, push
to Stack
+ 21 (12+9) + is an operator, pop
12 and 9 add them and
push result to Stack

Result: 21

Examples:  

Input : -+8/632
Output : 8

Input : -+7*45+20
Output : 25

Complexity The algorithm has linear complexity since we scan the expression once and perform at most O(N) push and pop operations which take constant time.
Implementation of the algorithm is given below.  

Implementation:

C++
// C++ program to evaluate a prefix expression.
#include <bits/stdc++.h>
using namespace std;

bool isOperand(char c)
{
    // If the character is a digit then it must
    // be an operand
    return isdigit(c);
}

double evaluatePrefix(string exprsn)
{
    stack<double> Stack;

    for (int j = exprsn.size() - 1; j >= 0; j--) {

        // Push operand to Stack
        // To convert exprsn[j] to digit subtract
        // '0' from exprsn[j].
        if (isOperand(exprsn[j]))
            Stack.push(exprsn[j] - '0');

        else {

            // Operator encountered
            // Pop two elements from Stack
            double o1 = Stack.top();
            Stack.pop();
            double o2 = Stack.top();
            Stack.pop();

            // Use switch case to operate on o1
            // and o2 and perform o1 Or o2.
            switch (exprsn[j]) {
            case '+':
                Stack.push(o1 + o2);
                break;
            case '-':
                Stack.push(o1 - o2);
                break;
            case '*':
                Stack.push(o1 * o2);
                break;
            case '/':
                Stack.push(o1 / o2);
                break;
            }
        }
    }

    return Stack.top();
}

// Driver code
int main()
{
    string exprsn = "+9*26";
    cout << evaluatePrefix(exprsn) << endl;
    return 0;
}
Java
// Java program to evaluate
// a prefix expression.
import java.io.*;
import java.util.*;

class GFG {

    static Boolean isOperand(char c)
    {
        // If the character is a digit
        // then it must be an operand
        if (c >= 48 && c <= 57)
            return true;
        else
            return false;
    }

    static double evaluatePrefix(String exprsn)
    {
        Stack<Double> Stack = new Stack<Double>();

        for (int j = exprsn.length() - 1; j >= 0; j--) {

            // Push operand to Stack
            // To convert exprsn[j] to digit subtract
            // '0' from exprsn[j].
            if (isOperand(exprsn.charAt(j)))
                Stack.push((double)(exprsn.charAt(j) - 48));

            else {

                // Operator encountered
                // Pop two elements from Stack
                double o1 = Stack.peek();
                Stack.pop();
                double o2 = Stack.peek();
                Stack.pop();

                // Use switch case to operate on o1
                // and o2 and perform o1 Or o2.
                switch (exprsn.charAt(j)) {
                case '+':
                    Stack.push(o1 + o2);
                    break;
                case '-':
                    Stack.push(o1 - o2);
                    break;
                case '*':
                    Stack.push(o1 * o2);
                    break;
                case '/':
                    Stack.push(o1 / o2);
                    break;
                }
            }
        }

        return Stack.peek();
    }

    /* Driver program to test above function */
    public static void main(String[] args)
    {
        String exprsn = "+9*26";
        System.out.println(evaluatePrefix(exprsn));
    }
}

// This code is contributed by Gitanjali
Python
"""
Python3 program to evaluate a prefix expression.
"""


def is_operand(c):
    """
    Return True if the given char c is an operand, e.g. it is a number
    """
    return c.isdigit()


def evaluate(expression):
    """
    Evaluate a given expression in prefix notation.
    Asserts that the given expression is valid.
    """
    stack = []

    # iterate over the string in reverse order
    for c in expression[::-1]:

        # push operand to stack
        if is_operand(c):
            stack.append(int(c))

        else:
            # pop values from stack can calculate the result
            # push the result onto the stack again
            o1 = stack.pop()
            o2 = stack.pop()

            if c == '+':
                stack.append(o1 + o2)

            elif c == '-':
                stack.append(o1 - o2)

            elif c == '*':
                stack.append(o1 * o2)

            elif c == '/':
                stack.append(o1 / o2)

    return stack.pop()


# Driver code
if __name__ == "__main__":
    test_expression = "+9*26"
    print(evaluate(test_expression))

# This code is contributed by Leon Morten Richter (GitHub: M0r13n)
C#
// C# program to evaluate
// a prefix expression.
using System;
using System.Collections.Generic;

class GFG {

    static Boolean isOperand(char c)
    {
        // If the character is a digit
        // then it must be an operand
        if (c >= 48 && c <= 57)
            return true;
        else
            return false;
    }

    static double evaluatePrefix(String exprsn)
    {
        Stack<Double> Stack = new Stack<Double>();

        for (int j = exprsn.Length - 1; j >= 0; j--) {

            // Push operand to Stack
            // To convert exprsn[j] to digit subtract
            // '0' from exprsn[j].
            if (isOperand(exprsn[j]))
                Stack.Push((double)(exprsn[j] - 48));

            else {

                // Operator encountered
                // Pop two elements from Stack
                double o1 = Stack.Peek();
                Stack.Pop();
                double o2 = Stack.Peek();
                Stack.Pop();

                // Use switch case to operate on o1
                // and o2 and perform o1 Or o2.
                switch (exprsn[j]) {
                case '+':
                    Stack.Push(o1 + o2);
                    break;
                case '-':
                    Stack.Push(o1 - o2);
                    break;
                case '*':
                    Stack.Push(o1 * o2);
                    break;
                case '/':
                    Stack.Push(o1 / o2);
                    break;
                }
            }
        }

        return Stack.Peek();
    }

    /* Driver code */
    public static void Main(String[] args)
    {
        String exprsn = "+9*26";
        Console.WriteLine(evaluatePrefix(exprsn));
    }
}

/* This code contributed by PrinciRaj1992 */
JavaScript
<script>
    // Javascript program to evaluate a prefix expression.
    
    function isOperand(c)
    {
        // If the character is a digit
        // then it must be an operand
        if (c.charCodeAt() >= 48 && c.charCodeAt() <= 57)
            return true;
        else
            return false;
    }
 
    function evaluatePrefix(exprsn)
    {
        let Stack = [];
 
        for (let j = exprsn.length - 1; j >= 0; j--) {
 
            // Push operand to Stack
            // To convert exprsn[j] to digit subtract
            // '0' from exprsn[j].
            if (isOperand(exprsn[j]))
                Stack.push((exprsn[j].charCodeAt() - 48));
 
            else {
 
                // Operator encountered
                // Pop two elements from Stack
                let o1 = Stack[Stack.length - 1];
                Stack.pop();
                let o2 = Stack[Stack.length - 1];
                Stack.pop();
 
                // Use switch case to operate on o1
                // and o2 and perform o1 Or o2.
                switch (exprsn[j]) {
                case '+':
                    Stack.push(o1 + o2);
                    break;
                case '-':
                    Stack.push(o1 - o2);
                    break;
                case '*':
                    Stack.push(o1 * o2);
                    break;
                case '/':
                    Stack.push(o1 / o2);
                    break;
                }
            }
        }
 
        return Stack[Stack.length - 1];
    }
    
    let exprsn = "+9*26";
      document.write(evaluatePrefix(exprsn));
    
    // This code is contributed by suresh07.
</script>

Output
21

Time Complexity: O(N)
Auxiliary Space: O(N)

Note: 
To perform more types of operations only the switch case table needs to be modified. This implementation works only for single digit operands. Multi-digit operands can be implemented if some character-like space is used to separate the operands and operators.

Below given is the extended program which allows operands to have multiple digits.

C++
// C++ program to evaluate a prefix expression.
#include <bits/stdc++.h>
using namespace std;

double evaluatePrefix(string exprsn)
{
    stack<double> Stack;

    for (int j = exprsn.size() - 1; j >= 0; j--) {
      
        // if jth character is the delimiter ( which is
        // space in this case) then skip it
        if (exprsn[j] == ' ')
            continue;

        // Push operand to Stack
        // To convert exprsn[j] to digit subtract
        // '0' from exprsn[j].
        if (isdigit(exprsn[j])) {
          
            // there may be more than 
            // one digits in a number
            double num = 0, i = j;
            while (j < exprsn.size() && isdigit(exprsn[j]))
                j--;
            j++;

            // from [j, i] exprsn contains a number
            for (int k = j; k <= i; k++)
                num = num * 10 + double(exprsn[k] - '0');

            Stack.push(num);
        }
        else {

            // Operator encountered
            // Pop two elements from Stack
            double o1 = Stack.top();
            Stack.pop();
            double o2 = Stack.top();
            Stack.pop();

            // Use switch case to operate on o1
            // and o2 and perform o1 O o2.
            switch (exprsn[j]) {
            case '+':
                Stack.push(o1 + o2);
                break;
            case '-':
                Stack.push(o1 - o2);
                break;
            case '*':
                Stack.push(o1 * o2);
                break;
            case '/':
                Stack.push(o1 / o2);
                break;
            }
        }
    }

    return Stack.top();
}

// Driver code
int main()
{
    string exprsn = "+ 9 * 12 6";
    cout << evaluatePrefix(exprsn) << endl;
    return 0;

    // this code is contributed by Mohd Shaad Khan
}
Java
// Java program to evaluate a prefix expression.
import java.util.*;
public class Main
{
    static boolean isdigit(char ch)
    {
        if(ch >= 48 && ch <= 57)
        {
            return true;
        }
        return false;
    }
     
    static double evaluatePrefix(String exprsn)
    {
        Stack<Double> stack = new Stack<Double>();
      
        for (int j = exprsn.length() - 1; j >= 0; j--) {
            
            // if jth character is the delimiter ( which is
            // space in this case) then skip it
            if (exprsn.charAt(j) == ' ')
                continue;
      
            // Push operand to Stack
            // To convert exprsn[j] to digit subtract
            // '0' from exprsn[j].
            if (isdigit(exprsn.charAt(j))) {
                
                // there may be more than
                // one digits in a number
                double num = 0, i = j;
                while (j < exprsn.length() && isdigit(exprsn.charAt(j)))
                    j--;
                j++;
      
                // from [j, i] exprsn contains a number
                for (int k = j; k <= i; k++)
                {
                    num = num * 10 + (double)(exprsn.charAt(k) - '0');
                }
      
                stack.push(num);
            }
            else {
      
                // Operator encountered
                // Pop two elements from Stack
                double o1 = (double)stack.peek();
                stack.pop();
                double o2 = (double)stack.peek();
                stack.pop();
      
                // Use switch case to operate on o1
                // and o2 and perform o1 O o2.
                switch (exprsn.charAt(j)) {
                case '+':
                    stack.push(o1 + o2);
                    break;
                case '-':
                    stack.push(o1 - o2);
                    break;
                case '*':
                    stack.push(o1 * o2);
                    break;
                case '/':
                    stack.push(o1 / o2);
                    break;
                }
            }
        }
      
        return stack.peek();
    }
    
  // Driver code
    public static void main(String[] args) {
        String exprsn = "+ 9 * 12 6";
        System.out.print((int)evaluatePrefix(exprsn));
    }
}

// This code is contributed by mukesh07.
Python
# Python3 program to evaluate a prefix expression.
def isdigit(ch):
    if(ord(ch) >= 48 and ord(ch) <= 57):
        return True
    return False
 
def evaluatePrefix(exprsn):
    Stack = []

    for j in range(len(exprsn) - 1, -1, -1):
      
        # if jth character is the delimiter ( which is
        # space in this case) then skip it
        if (exprsn[j] == ' '):
            continue
            
        # Push operand to Stack
        # To convert exprsn[j] to digit subtract
        # '0' from exprsn[j].
        if (isdigit(exprsn[j])):
          
            # there may be more than
            # one digits in a number
            num, i = 0, j
            while (j < len(exprsn) and isdigit(exprsn[j])):
                j-=1
            j+=1

            # from [j, i] exprsn contains a number
            for k in range(j, i + 1, 1):
                num = num * 10 + (ord(exprsn[k]) - ord('0'))

            Stack.append(num)
        else:
            # Operator encountered
            # Pop two elements from Stack
            o1 = Stack[-1]
            Stack.pop()
            o2 = Stack[-1]
            Stack.pop()

            # Use switch case to operate on o1
            # and o2 and perform o1 O o2.
            if exprsn[j] == '+':
                Stack.append(o1 + o2 + 12)
            elif exprsn[j] == '-':
                Stack.append(o1 - o2)
            elif exprsn[j] == '*':
                Stack.append(o1 * o2 * 5 )
            elif exprsn[j] == '/':
                Stack.append(o1 / o2)
                
    return Stack[-1]

exprsn = "+ 9 * 12 6"
print(evaluatePrefix(exprsn))

# This code is contributed by divyesh072019.
C#
// C# program to evaluate a prefix expression.
using System;
using System.Collections;
class GFG {
    
    static bool isdigit(char ch)
    {
        if(ch >= 48 && ch <= 57)
        {
            return true;
        }
        return false;
    }
    
    static double evaluatePrefix(string exprsn)
    {
        Stack stack = new Stack();
     
        for (int j = exprsn.Length - 1; j >= 0; j--) {
           
            // if jth character is the delimiter ( which is
            // space in this case) then skip it
            if (exprsn[j] == ' ')
                continue;
     
            // Push operand to Stack
            // To convert exprsn[j] to digit subtract
            // '0' from exprsn[j].
            if (isdigit(exprsn[j])) {
               
                // there may be more than
                // one digits in a number
                double num = 0, i = j;
                while (j < exprsn.Length && isdigit(exprsn[j]))
                    j--;
                j++;
     
                // from [j, i] exprsn contains a number
                for (int k = j; k <= i; k++)
                {
                    num = num * 10 + (double)(exprsn[k] - '0');
                }
     
                stack.Push(num);
            }
            else {
     
                // Operator encountered
                // Pop two elements from Stack
                double o1 = (double)stack.Peek();
                stack.Pop();
                double o2 = (double)stack.Peek();
                stack.Pop();
     
                // Use switch case to operate on o1
                // and o2 and perform o1 O o2.
                switch (exprsn[j]) {
                case '+':
                    stack.Push(o1 + o2);
                    break;
                case '-':
                    stack.Push(o1 - o2);
                    break;
                case '*':
                    stack.Push(o1 * o2);
                    break;
                case '/':
                    stack.Push(o1 / o2);
                    break;
                }
            }
        }
     
        return (double)stack.Peek();
    }
    
  static void Main() {
    string exprsn = "+ 9 * 12 6";
    Console.Write(evaluatePrefix(exprsn));
  }
}

// This code is contributed by divyeshrabadiya07.
JavaScript
<script>
    // Javascript program to evaluate a prefix expression.
    
    function isdigit(ch)
    {
        if(ch.charCodeAt() >= 48 && ch.charCodeAt() <= 57)
        {
            return true;
        }
        return false;
    }
    
    function evaluatePrefix(exprsn)
    {
        let Stack = [];

        for (let j = exprsn.length - 1; j >= 0; j--) {

            // if jth character is the delimiter ( which is
            // space in this case) then skip it
            if (exprsn[j] == ' ')
                continue;

            // Push operand to Stack
            // To convert exprsn[j] to digit subtract
            // '0' from exprsn[j].
            if (isdigit(exprsn[j])) {

                // there may be more than
                // one digits in a number
                let num = 0, i = j;
                while (j < exprsn.length && isdigit(exprsn[j]))
                    j--;
                j++;

                // from [j, i] exprsn contains a number
                for (let k = j; k <= i; k++)
                    num = num * 10 + (exprsn[k].charCodeAt() - '0'.charCodeAt());

                Stack.push(num);
            }
            else {

                // Operator encountered
                // Pop two elements from Stack
                let o1 = Stack[Stack.length - 1];
                Stack.pop();
                let o2 = Stack[Stack.length - 1];
                Stack.pop();

                // Use switch case to operate on o1
                // and o2 and perform o1 O o2.
                switch (exprsn[j]) {
                case '+':
                    Stack.push(o1 + o2);
                    break;
                case '-':
                    Stack.push(o1 - o2);
                    break;
                case '*':
                    Stack.push(o1 * o2);
                    break;
                case '/':
                    Stack.push(o1 / o2);
                    break;
                }
            }
        }

        return Stack[Stack.length - 1];
    }
    
    let exprsn = "+ 9 * 12 6";
    document.write(evaluatePrefix(exprsn));

// This code is contributed by rameshtravel07.
</script>

Output
81

Time Complexity: O(n)
Auxiliary Space: O(n)



Similar Reads

Infix, Postfix and Prefix Expressions/Notations
Mathematical formulas often involve complex expressions that require a clear understanding of the order of operations. To represent these expressions, we use different notations, each with its own advantages and disadvantages. In this article, we will explore three common expression notations: infix, prefix, and postfix. Table of Content Infix Expr
6 min read
Maximum sum increasing subsequence from a prefix and a given element after prefix is must
Given an array of n positive integers, write a program to find the maximum sum of increasing subsequence from prefix till ith index and also including a given kth element which is after i, i.e., k &gt; i. Examples : Input: arr[] = {1, 101, 2, 3, 100, 4, 5} i-th index = 4 (Element at 4th index is 100) K-th index = 6 (Element at 6th index is 5.) Outp
14 min read
Check if count of substrings in S with string S1 as prefix and S2 as suffix is equal to that with S2 as prefix and S1 as suffix
Given three strings S, S1, and S2, the task is to check if the number of substrings that start and end with S1 and S2 is equal to the number of substrings that start and end with S2 and S1 or not. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = "helloworldworldhelloworld", S1 = "hello", S2 = "world"Output: NoExpla
8 min read
Maximum prefix sum which is equal to suffix sum such that prefix and suffix do not overlap
Given an array arr[] of N Positive integers, the task is to find the largest prefix sum which is also the suffix sum and prefix and suffix do not overlap. Examples: Input: N = 5, arr = [1, 3, 2, 1, 4]Output: 4Explanation: consider prefix [1, 3] and suffix [4] which gives maximum prefix sum which is also suffix sum such that prefix and suffix do not
7 min read
Expression Evaluation
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
15 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
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
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
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
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
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
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
Extracting email addresses using regular expressions in Python
Let suppose a situation in which you have to read some specific data like phone numbers, email addresses, dates, a collection of words etc. How can you do this in a very efficient manner?The Best way to do this by Regular Expression. Let take an example in which we have to find out only email from the given input by Regular Expression. Examples: In
3 min read
Regular Expressions to Validate Google Analytics Tracking Id
Given some Google Analytics Tracking IDs, the task is to check if they are valid or not using regular expressions. Rules for the valid Tracking Id are: It is an alphanumeric string i.e., containing digits (0-9), alphabets (A-Z), and a Special character hyphen(-).The hyphen will come in between the given Google Analytics Tracking Id.Google Analytics
5 min read
Balanced expressions such that given positions have opening brackets | Set 2
Given an integer n and an array of positions ‘position[]’ (1 &lt;= length(position[]) &lt;= 2n), find the number of ways of proper bracket expressions that can be formed of length 2n such that given positions have the opening bracket. Note: position[] array is given in the form of (1-based indexing) [0, 1, 1, 0]. Here 1 denotes the positions at whi
15+ min read
Number of balanced bracket expressions that can be formed from a string
Given a string str comprising of characters (, ), {, }, [, ] and ?. The task is to find the total number of balanced bracket expressions formed when ? can be replaced with any of the bracket characters. Here are some examples of balanced bracket expressions: {([])}, {()}[{}] etc. And, unbalanced bracket expressions: {[}, {()], {()}[) etc. Examples:
12 min read
Check if the given Binary Expressions are valid
Given n expressions of the type x = y and x != y where 1 ? x, y ? n, the task is to check whether the integers from 1 to n can be assigned to x and y such that all the equations are satisfied. Examples: Input: x[] = {1, 2, 3}, op[] = {"=", "=", "!="}, y[] = {2, 3, 1} Output: Invalid If 1 = 2 and 2 = 3 then 3 must be equal to 1. Input: x[] = {1, 2},
10 min read
How to validate a Username using Regular Expressions in Java
Given a string str which represents a username, the task is to validate this username with the help of Regular Expressions. A username is considered valid if all the following constraints are satisfied: The username consists of 6 to 30 characters inclusive. If the username consists of less than 6 or greater than 30 characters, then it is an invalid
3 min read
Print all the possible arithmetic expressions for a given number
Given an integer N, the task is to print all the possible arithmetic expressions using all numbers from 1 to N and with binary operator +, –, * and /.Examples: Input: n = 2 Output: 1+2, 1-2, 1/2, 1*2Input: n = 3 Output: 1+2+3, 1+2-3, 1+2/3, 1+2*3, 1-2+3, 1-2-3, 1-2/3, 1-2*3 1/2+3, 1/2-3, 1/2/3, 1/2*3, 1*2+3, 1*2-3, 1*2/3, 1*2*3 Approach: We will cr
5 min read
Sum of all possible expressions of a numeric string possible by inserting addition operators
Given a numeric string str of length N, the task is to find the sum of all possible expressions by inserting the '+' operator between the characters of the string any number of times. Examples: Input: str = "125" Output: 176 Explanation: Inserting "+" after 1st index modifies str to "1+25" and value = 26 Inserting "+" after 2nd index modifies str t
8 min read
Regular Expressions to Validate Provident Fund(PF) Account Number
Given some PF(Provident Fund) Account Number, the task is to check if they are valid or not using regular expressions. Rules for the valid PF Account Number are : PF account number is alphanumeric String and forward slaces.First five characters are reserved for alphabet letters.Next 17 characters are reserved for digits(0-9).It allows only special
5 min read
Count occurrences of a word in string | Set 2 (Using Regular Expressions)
Given a string str and a word w, the task is to print the number of the occurrence of the given word in the string str using Regular Expression. Examples: Input: str = "peter parker picked a peck of pickled peppers”, w = "peck"Output: 1Explanation: There is only one occurrence of the word "peck" in the given string. Therefore, the output is 1. Inpu
4 min read
US currency validation using Regular Expressions
Given some US Currencies, the task is to check if they are valid or not using regular expressions. Rules for the valid Currency are: It should always start with "$".It can contain only digits (0 - 9) and at most one dot.It should not contain any whitespaces and alphabets.Comma Separator (', ') should be there after every three digits interval. Exam
5 min read
Extracting PAN Number from GST Number Using Regular Expressions
Given a string str in the form of a GST Number, the task is to extract the PAN Number from the given string. General Format of a GST Number: "22AAAAA0000A1Z5" 22: State CodeAAAAA0000A: Permanent Account Number (PAN)1: Entity Number of the same PANZ: Alphabet Z by default5: Checksum digit Examples: Input: str="23BOSPC9911R2Z5Output: BOSPC9911R Input
4 min read
How to validate ISIN using Regular Expressions
ISIN stands for International Securities Identification Number. Given string str, the task is to check whether the given string is a valid ISIN(International Securities Identification Number) or not by using Regular Expression. The valid ISIN(International Securities Identification Number) must satisfy the following conditions: It Should be the com
6 min read
Validating UPI IDs using Regular Expressions
Given some UPI IDs, the task is to check if they are valid or not using regular expressions. Rules for the valid UPI ID: UPI ID is an alphanumeric String i.e., formed using digits(0-9), alphabets (A-Z and a-z), and other special characters.It must contain '@'.It should not contain whitespace.It may or may not contain a dot (.) or hyphen (-). UPI st
6 min read
Validate Gender using Regular Expressions
Given some words of Gender, the task is to check if they are valid or not using regular expressions. The correct responses can be as given below: Male / male / MALE / M / mFemale / female / FEMALE / F / fNot prefer to say Example: Input: MOutput: True Input: SOutput: False Approach: The problem can be solved based on the following idea: Create a re
6 min read
Validating Programming File formats using Regular Expressions
Given some programming file names, the task is to check if they are valid or not using regular expressions. A valid programming file name follows the below conditions: It can contain alphabets (UpperCase or LowerCase), and digits and may contain a hyphen.It should contain one dot only that will be used as a suffix to save the file.Avoid special cha
6 min read
Practice Tags :
three90RightbarBannerImg