The Wayback Machine - https://web.archive.org/web/20240911070146/https://www.geeksforgeeks.org/convert-infix-expression-to-postfix-expression/
Open In App

Convert Infix expression to Postfix expression

Last Updated : 24 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
52.94%
93.3K

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 + D
Output: ABC*+D+

Input: ((A + B) – C * (D / E)) + F
Output: AB+CDE/*-F+  

Why postfix representation of the expression? 

The compiler scans the expression either from left to right or from right to left. 
Consider the expression: a + b * c + d

  • The compiler first scans the expression to evaluate the expression b * c, then again scans the expression to add a to it. 
  • The result is then added to d after another scan. 

The repeated scanning makes it very inefficient. Infix expressions are easily readable and solvable by humans whereas the computer cannot differentiate the operators and parenthesis easily so, it is better to convert the expression to postfix(or prefix) form before evaluation.

The corresponding expression in postfix form is abc*+d+. The postfix expressions can be evaluated easily using a stack. 

How to convert an Infix expression to a Postfix expression?

To convert infix expression to postfix expression, use the stack data structure. Scan the infix expression from left to right. Whenever we get an operand, add it to the postfix expression and if we get an operator or parenthesis add it to the stack by maintaining their precedence.

Below are the steps to implement the above idea:

  1. Scan the infix expression from left to right. 
  2. If the scanned character is an operand, put it in the postfix expression. 
  3. Otherwise, do the following
    • If the precedence and associativity of the scanned operator are greater than the precedence and associativity of the operator in the stack [or the stack is empty or the stack contains a ‘(‘ ], then push it in the stack. [‘^‘ operator is right associative and other operators like ‘+‘,’–‘,’*‘ and ‘/‘ are left-associative].
      • Check especially for a condition when the operator at the top of the stack and the scanned operator both are ‘^‘. In this condition, the precedence of the scanned operator is higher due to its right associativity. So it will be pushed into the operator stack. 
      • In all the other cases when the top of the operator stack is the same as the scanned operator, then pop the operator from the stack because of left associativity due to which the scanned operator has less precedence. 
    • Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator.
      • After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping then stop there and push the scanned operator in the stack.) 
  4. If the scanned character is a ‘(‘, push it to the stack. 
  5. If the scanned character is a ‘)’, pop the stack and output it until a ‘(‘ is encountered, and discard both the parenthesis. 
  6. Repeat steps 2-5 until the infix expression is scanned. 
  7. Once the scanning is over, Pop the stack and add the operators in the postfix expression until it is not empty.
  8. Finally, print the postfix expression.

Illustration:

Follow the below illustration for a better understanding

Consider the infix expression exp = “a+b*c+d”
and the infix expression is scanned using the iterator i, which is initialized as i = 0.

1st Step: Here i = 0 and exp[i] = ‘a’ i.e., an operand. So add this in the postfix expression. Therefore, postfix = “a”.

Add 'a' in the postfix

Add ‘a’ in the postfix

2nd Step: Here i = 1 and exp[i] = ‘+’ i.e., an operator. Push this into the stack. postfix = “a” and stack = {+}.

Push '+' in the stack

Push ‘+’ in the stack

3rd Step: Now i = 2 and exp[i] = ‘b’ i.e., an operand. So add this in the postfix expression. postfix = “ab” and stack = {+}.

gfg

Add ‘b’ in the postfix

4th Step: Now i = 3 and exp[i] = ‘*’ i.e., an operator. Push this into the stack. postfix = “ab” and stack = {+, *}.

Push '*' in the stack

Push ‘*’ in the stack

5th Step: Now i = 4 and exp[i] = ‘c’ i.e., an operand. Add this in the postfix expression. postfix = “abc” and stack = {+, *}.

Add 'c' in the postfix

Add ‘c’ in the postfix

6th Step: Now i = 5 and exp[i] = ‘+’ i.e., an operator. The topmost element of the stack has higher precedence. So pop until the stack becomes empty or the top element has less precedence. ‘*’ is popped and added in postfix. So postfix = “abc*” and stack = {+}. 

Pop '*' and add in postfix

Pop ‘*’ and add in postfix

Now top element is ‘+‘ that also doesn’t have less precedence. Pop it. postfix = “abc*+”. 

Pop '+' and add it in postfix

Pop ‘+’ and add it in postfix

Now stack is empty. So push ‘+’ in the stack. stack = {+}.

Push '+' in the stack

Push ‘+’ in the stack

7th Step: Now i = 6 and exp[i] = ‘d’ i.e., an operand. Add this in the postfix expression. postfix = “abc*+d”.

Add 'd' in the postfix

Add ‘d’ in the postfix

Final Step: Now no element is left. So empty the stack and add it in the postfix expression. postfix = “abc*+d+”.

Pop '+' and add it in postfix

Pop ‘+’ and add it in postfix

Below is the implementation of the above algorithm: 

C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Function to return precedence of operators
int prec(char c) {
    if (c == '^')
        return 3;
    else if (c == '/' || c == '*')
        return 2;
    else if (c == '+' || c == '-')
        return 1;
    else
        return -1;
}

// Function to return associativity of operators
char associativity(char c) {
    if (c == '^')
        return 'R';
    return 'L'; // Default to left-associative
}

// The main function to convert infix expression to postfix expression
void infixToPostfix(char s[]) {
    char result[1000];
    int resultIndex = 0;
    int len = strlen(s);
    char stack[1000];
    int stackIndex = -1;

    for (int i = 0; i < len; i++) {
        char c = s[i];

        // If the scanned character is an operand, add it to the output string.
        if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
            result[resultIndex++] = c;
        }
        // If the scanned character is an ‘(‘, push it to the stack.
        else if (c == '(') {
            stack[++stackIndex] = c;
        }
        // If the scanned character is an ‘)’, pop and add to the output string from the stack
        // until an ‘(‘ is encountered.
        else if (c == ')') {
            while (stackIndex >= 0 && stack[stackIndex] != '(') {
                result[resultIndex++] = stack[stackIndex--];
            }
            stackIndex--; // Pop '('
        }
        // If an operator is scanned
        else {
            while (stackIndex >= 0 && (prec(s[i]) < prec(stack[stackIndex]) ||
                                       prec(s[i]) == prec(stack[stackIndex]) &&
                                           associativity(s[i]) == 'L')) {
                result[resultIndex++] = stack[stackIndex--];
            }
            stack[++stackIndex] = c;
        }
    }

    // Pop all the remaining elements from the stack
    while (stackIndex >= 0) {
        result[resultIndex++] = stack[stackIndex--];
    }

    result[resultIndex] = '\0';
    printf("%s\n", result);
}

// Driver code
int main() {
    char exp[] = "a+b*(c^d-e)^(f+g*h)-i";

    // Function call
    infixToPostfix(exp);

    return 0;
}
Java
import java.util.Stack;

public class InfixToPostfix {

    // Function to return precedence of operators
    static int prec(char c) {
        if (c == '^')
            return 3;
        else if (c == '/' || c == '*')
            return 2;
        else if (c == '+' || c == '-')
            return 1;
        else
            return -1;
    }

    // Function to return associativity of operators
    static char associativity(char c) {
        if (c == '^')
            return 'R';
        return 'L'; // Default to left-associative
    }

    // The main function to convert infix expression to postfix expression
    static void infixToPostfix(String s) {
        StringBuilder result = new StringBuilder();
        Stack<Character> stack = new Stack<>();

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

            // If the scanned character is an operand, add it to the output string.
            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
                result.append(c);
            }
            // If the scanned character is an ‘(‘, push it to the stack.
            else if (c == '(') {
                stack.push(c);
            }
            // If the scanned character is an ‘)’, pop and add to the output string from the stack
            // until an ‘(‘ is encountered.
            else if (c == ')') {
                while (!stack.isEmpty() && stack.peek() != '(') {
                    result.append(stack.pop());
                }
                stack.pop(); // Pop '('
            }
            // If an operator is scanned
            else {
                while (!stack.isEmpty() && (prec(s.charAt(i)) < prec(stack.peek()) ||
                                             prec(s.charAt(i)) == prec(stack.peek()) &&
                                                 associativity(s.charAt(i)) == 'L')) {
                    result.append(stack.pop());
                }
                stack.push(c);
            }
        }

        // Pop all the remaining elements from the stack
        while (!stack.isEmpty()) {
            result.append(stack.pop());
        }

        System.out.println(result);
    }

    // Driver code
    public static void main(String[] args) {
        String exp = "a+b*(c^d-e)^(f+g*h)-i";

        // Function call
        infixToPostfix(exp);
    }
}
Python
def prec(c):
    if c == '^':
        return 3
    elif c == '/' or c == '*':
        return 2
    elif c == '+' or c == '-':
        return 1
    else:
        return -1

def associativity(c):
    if c == '^':
        return 'R'
    return 'L'  # Default to left-associative

def infix_to_postfix(s):
    result = []
    stack = []

    for i in range(len(s)):
        c = s[i]

        # If the scanned character is an operand, add it to the output string.
        if ('a' <= c <= 'z') or ('A' <= c <= 'Z') or ('0' <= c <= '9'):
            result.append(c)
        # If the scanned character is an ‘(‘, push it to the stack.
        elif c == '(':
            stack.append(c)
        # If the scanned character is an ‘)’, pop and add to the output string from the stack
        # until an ‘(‘ is encountered.
        elif c == ')':
            while stack and stack[-1] != '(':
                result.append(stack.pop())
            stack.pop()  # Pop '('
        # If an operator is scanned
        else:
            while stack and (prec(s[i]) < prec(stack[-1]) or
                             (prec(s[i]) == prec(stack[-1]) and associativity(s[i]) == 'L')):
                result.append(stack.pop())
            stack.append(c)

    # Pop all the remaining elements from the stack
    while stack:
        result.append(stack.pop())

    print(''.join(result))

# Driver code
exp = "a+b*(c^d-e)^(f+g*h)-i"

# Function call
infix_to_postfix(exp)
C#
using System;
using System.Collections.Generic;

class Program
{
    // Function to return precedence of operators
    static int Prec(char c)
    {
        if (c == '^')
            return 3;
        else if (c == '/' || c == '*')
            return 2;
        else if (c == '+' || c == '-')
            return 1;
        else
            return -1;
    }

    // Function to return associativity of operators
    static char Associativity(char c)
    {
        if (c == '^')
            return 'R';
        return 'L'; // Default to left-associative
    }

    // The main function to convert infix expression to postfix expression
    static void InfixToPostfix(string s)
    {
        Stack<char> stack = new Stack<char>();
        List<char> result = new List<char>();

        for (int i = 0; i < s.Length; i++)
        {
            char c = s[i];

            // If the scanned character is an operand, add it to the output string.
            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
            {
                result.Add(c);
            }
            // If the scanned character is an ‘(‘, push it to the stack.
            else if (c == '(')
            {
                stack.Push(c);
            }
            // If the scanned character is an ‘)’, pop and add to the output string from the stack
            // until an ‘(‘ is encountered.
            else if (c == ')')
            {
                while (stack.Count > 0 && stack.Peek() != '(')
                {
                    result.Add(stack.Pop());
                }
                stack.Pop(); // Pop '('
            }
            // If an operator is scanned
            else
            {
                while (stack.Count > 0 && (Prec(s[i]) < Prec(stack.Peek()) ||
                                           Prec(s[i]) == Prec(stack.Peek()) &&
                                               Associativity(s[i]) == 'L'))
                {
                    result.Add(stack.Pop());
                }
                stack.Push(c);
            }
        }

        // Pop all the remaining elements from the stack
        while (stack.Count > 0)
        {
            result.Add(stack.Pop());
        }

        Console.WriteLine(string.Join("", result));
    }

    // Driver code
    static void Main()
    {
        string exp = "a+b*(c^d-e)^(f+g*h)-i";

        // Function call
        InfixToPostfix(exp);
    }
}
JavaScript
    /* Javascript implementation to convert
    infix expression to postfix*/
    
    //Function to return precedence of operators
    function prec(c) {
        if(c == '^')
            return 3;
        else if(c == '/' || c=='*')
            return 2;
        else if(c == '+' || c == '-')
            return 1;
        else
            return -1;
    }

    // The main function to convert infix expression
    //to postfix expression
    function infixToPostfix(s) {

        let st = []; //For stack operations, we are using JavaScript built in stack
        let result = "";

        for(let i = 0; i < s.length; i++) {
            let c = s[i];

            // If the scanned character is
            // an operand, add it to output string.
            if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
                result += c;

            // If the scanned character is an
            // ‘(‘, push it to the stack.
            else if(c == '(')
                st.push('(');

            // If the scanned character is an ‘)’,
            // pop and to output string from the stack
            // until an ‘(‘ is encountered.
            else if(c == ')') {
                while(st[st.length - 1] != '(')
                {
                    result += st[st.length - 1];
                    st.pop();
                }
                st.pop();
            }

            //If an operator is scanned
            else {
                while(st.length != 0 && prec(s[i]) <= prec(st[st.length - 1])) {
                    result += st[st.length - 1];
                    st.pop(); 
                }
                st.push(c);
            }
        }

        // Pop all the remaining elements from the stack
        while(st.length != 0) {
            result += st[st.length - 1];
            st.pop();
        }

        console.log(result + "</br>");
    }
    
    let exp = "a+b*(c^d-e)^(f+g*h)-i";
    infixToPostfix(exp);

// This code is contributed by decode2207.
C++14
#include <bits/stdc++.h>
using namespace std;

// Function to return precedence of operators
int prec(char c) {
    if (c == '^')
        return 3;
    else if (c == '/' || c == '*')
        return 2;
    else if (c == '+' || c == '-')
        return 1;
    else
        return -1;
}

// Function to return associativity of operators
char associativity(char c) {
    if (c == '^')
        return 'R';
    return 'L'; // Default to left-associative
}

// The main function to convert infix expression
// to postfix expression
void infixToPostfix(string s) {
    stack<char> st;
    string result;

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

        // If the scanned character is
        // an operand, add it to the output string.
        if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
            result += c;

        // If the scanned character is an
        // ‘(‘, push it to the stack.
        else if (c == '(')
            st.push('(');

        // If the scanned character is an ‘)’,
        // pop and add to the output string from the stack
        // until an ‘(‘ is encountered.
        else if (c == ')') {
            while (st.top() != '(') {
                result += st.top();
                st.pop();
            }
            st.pop(); // Pop '('
        }

        // If an operator is scanned
        else {
            while (!st.empty() && prec(s[i]) < prec(st.top()) ||
                   !st.empty() && prec(s[i]) == prec(st.top()) &&
                   associativity(s[i]) == 'L') {
                result += st.top();
                st.pop();
            }
            st.push(c);
        }
    }

    // Pop all the remaining elements from the stack
    while (!st.empty()) {
        result += st.top();
        st.pop();
    }

    cout << result << endl;
}

// Driver code
int main() {
    string exp = "a+b*(c^d-e)^(f+g*h)-i";

    // Function call
    infixToPostfix(exp);

    return 0;
}

Output
abcd^e-fgh*+^*+i-

Time Complexity: O(N), where N is the size of the infix expression
Auxiliary Space: O(N), where N is the size of the infix expression

 



Previous Article
Next Article

Similar Reads

Postfix to Infix
Infix expression: The expression of the form a op b. When an operator is in-between every pair of operands. Postfix expression: The expression of the form a b op. When an operator is followed for every pair of operands. Postfix notation, also known as reverse Polish notation, is a syntax for mathematical expressions in which the mathematical operat
7 min read
Infix to Postfix Converter using JavaScript
Postfix expressions are easier for a compiler to understand and evaluate. So this is a converter that converts infix expression to postfix expression using JavaScript. Pre-requisites: Stack operationInfix to Postfix conversionBasic JavaScript Approach: Button Convert call function InfixtoPostfix() and this function converts the given infix expressi
4 min read
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
Program to convert Infix notation to Expression Tree
Given a string representing infix notation. The task is to convert it to an expression tree.Expression Tree is a binary tree where the operands are represented by leaf nodes and operators are represented by intermediate nodes. No node can have a single child. Construction of Expression tree The algorithm follows a combination of shunting yard along
12 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
Convert Infix To Prefix Notation
Given an infix expression, the task is to convert it to a prefix expression. Infix Expression: The expression of type a 'operator' b (a+b, where + is an operator) i.e., when the operator is between two operands. Prefix Expression: The expression of type 'operator' a b (+ab where + is an operator) i.e., when the operator is placed before the operand
12 min read
Infix to Prefix conversion using two stacks
Infix: An expression is called the Infix expression if the operator appears in between the operands in the expression. Simply of the form (operand1 operator operand2). Example : (A+B) * (C-D) Prefix: An expression is called the prefix expression if the operator appears in the expression before the operands. Simply of the form (operator operand1 ope
13 min read
Prefix to Infix Conversion
Infix : An expression is called the Infix expression if the operator appears in between the operands in the expression. Simply of the form (operand1 operator operand2). Example : (A+B) * (C-D) Prefix : An expression is called the prefix expression if the operator appears in the expression before the operands. Simply of the form (operator operand1 o
6 min read
Postfix to Prefix Conversion
Postfix: An expression is called the postfix expression if the operator appears in the expression after the operands. Simply of the form (operand1 operand2 operator). Example : AB+CD-* (Infix : (A+B) * (C-D) ) Prefix : An expression is called the prefix expression if the operator appears in the expression before the operands. Simply of the form (op
7 min read
Why do we need Prefix and Postfix notations?
Prefix Notation: Prefix notation is the notation in which operators are placed before the corresponding operands in the expression. Example: Infix notation: A + B Prefix notation: +AB Postfix Notation: Postfix notation is the notation in which operators are placed after the corresponding operands in the expression. Example: Infix notation: A + B Po
1 min read
Prefix to Postfix Converter Online
Prefix to Postfix Calculator is a free online tool to calculate the postfix of a prefix notation. In this converter user has to put the prefix notation in the input box and postfix notation will be displayed as a result. Prefix Expression: An expression is called the prefix expression if the operator appears in the expression before the operands. S
2 min read
Find original Array from given Array where each element is sum of prefix and postfix sum
Given an array arr[] of length N, where arr is derived from an array nums[] which is lost. Array arr[] is derived as: arr[i] = (nums[0] + nums[1] + ... + nums[i]) + (nums[i] + nums[i+1] + ... + nums[N-1]). The task is to find nums[] array of length N. Examples: Input: N = 4, arr[] = {9, 10, 11, 10}Output: {1, 2, 3, 2}Explanation: If nums[] = {1, 2,
10 min read
Prefix to Postfix Conversion
Given a Prefix expression, convert it into a Postfix expression. Conversion of Prefix expression directly to Postfix without going through the process of converting them first to Infix and then to Postfix is much better in terms of computation and better understanding the expression (Computers evaluate using Postfix expression). let's discuss about
6 min read
Online Postfix to Prefix Converter
Our Postfix to Prefix converter tool helps you convert an expression written in postfix notation (Reverse Polish Notation) to its equivalent prefix notation (Polish Notation). Convert your postfix expressions to prefix notation easily with this free online tool. How to Use Postfix to Prefix Converter?Step 1: Enter your postfix expression in the tex
2 min read
Convert Ternary Expression to a Binary Tree
Given a string that contains ternary expressions. The expressions may be nested, task is convert the given ternary expression to a binary Tree. Examples: Input : string expression = a?b:c Output : a / \ b cInput : expression = a?b?c:d:eOutput : a / \ b e / \ c dAsked In : Facebook Interview Idea is that we traverse a string make first character as
11 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
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
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
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
Practice Tags :