Evaluation of Prefix Expressions (original) (raw)

Last Updated : 15 Sep, 2025

Given an array of strings **arr[] representing a prefix expression, we have to evaluate it. A prefix expression is of the form "operator operand1 operand2" (e.g., +ab), where the operator is written before its two operands.

**Note: The operators can include +, -, *, /, and ^ (where ^ denotes exponentiation, i.e., power). Division / uses floor division.

**Examples:

**Input: arr[] = ["+", "*", "/", "+", "100", "200", "2", "5", "7"]
**Output: 757
**Explanation: The expression can be written in infix form as: (((100 + 200) / 2) * 5) + 7. Now, evaluate step by step:
100 + 200 = 300
300 / 2 = 150
150 * 5 = 750
750 + 7 = 757
Final Answer: 757

**Input: arr[] = ["^", "+", "2", "3", "2"]
**Output: 25
**Explanation: The expression can be written in infix form as: (2 + 3) ^ 2. First, add 2 and 3 to get 5, then raise 5 to the power 2 to get 25.

Try It Yourselfredirect icon

[Approach] Using Stack - O(n) Time and O(n) Space

The idea is to use a stack. In prefix notation, every operator comes before its operands (e.g., +23). So while evaluating, we scan the expression from right to left. If we find an operand, push it into the stack and if we find an operator, pop the top two elements, apply the operator, and push the result back.

**Why traverse from Right to Left?

Prefix is of the form "operator operand1 operand2". If we scan from left to right, we’ll encounter the operator first, but we won’t yet have the operands needed to apply it. By scanning from right to left, we first push operands onto the stack. This way, when an operator comes, the required operands are already available in the stack.

C++ `

#include #include #include #include using namespace std;

int floorDiv(int a, int b) { if (a * b < 0 && a % b != 0) return (a / b) - 1; return a / b; }

int evaluatePrefix(vector& arr) { stack st; int n = arr.size();

// Traverse from right to left
for (int i = n - 1; i >= 0; i--) {
    string token = arr[i];

    // If it's an operand (number), push it onto the stack
    if (isdigit(token[0]) || (token.size() > 1 && token[0] == '-')) {
        st.push(stoi(token));
    }

    // Otherwise, it must be an operator
    else {
        int val1 = st.top(); st.pop();
        int val2 = st.top(); st.pop();

        if (token == "+") {
            st.push(val1 + val2);
        } else if (token == "-") {
            st.push(val1 - val2);
        } else if (token == "*") {
            st.push(val1 * val2);
        } else if (token == "/") {
            st.push(floorDiv(val1, val2));
        } else if (token == "^") {
            st.push(pow(val1, val2));
        }
    }
}
return st.top();

}

int main() { vector arr = {"+", "*", "/", "+", "100", "200", "2", "5", "7"}; cout << evaluatePrefix(arr) << endl; return 0; }

C

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h>

// Simple stack implementation #define MAX 1000 int st[MAX]; int top = -1;

void push(int x) { st[++top] = x; }

int pop() { return st[top--]; }

int floorDiv(int a, int b) { if (a * b < 0 && a % b != 0) return (a / b) - 1; return a / b; }

int evaluatePrefix(char* arr[], int n) { // Traverse from right to left for (int i = n - 1; i >= 0; i--) { char* token = arr[i];

    // If it's an operand (number), push it onto the stack
    if (isdigit(token[0]) || (strlen(token) > 1 && token[0] == '-')) {
        push(atoi(token));
    }
    // Otherwise, it must be an operator
    else {
        int val1 = pop();
        int val2 = pop();

        if (strcmp(token, "+") == 0) {
            push(val1 + val2);
        } else if (strcmp(token, "-") == 0) {
            push(val1 - val2);
        } else if (strcmp(token, "*") == 0) {
            push(val1 * val2);
        } else if (strcmp(token, "/") == 0) {
            push(floorDiv(val1, val2));
        } else if (strcmp(token, "^") == 0) {
            push((int)pow(val1, val2));
        }
    }
}
return pop();

}

int main() { char* arr[] = {"+", "*", "/", "+", "100", "200", "2", "5", "7"}; int n = sizeof(arr) / sizeof(arr[0]); printf("%d\n", evaluatePrefix(arr, n)); return 0; }

Java

import java.util.Stack;

public class GFG {

static int floorDiv(int a, int b) {
    if (a * b < 0 && a % b != 0)
        return (a / b) - 1;
    return a / b;
}

public static int evaluatePrefix(String[] arr) {
    Stack<Integer> st = new Stack<>();
    int n = arr.length;

    // Traverse from right to left
    for (int i = n - 1; i >= 0; i--) {
        String token = arr[i];

        // If it's an operand (number), push it onto the stack
        if (Character.isDigit(token.charAt(0)) || 
           (token.length() > 1 && token.charAt(0) == '-')) {
            st.push(Integer.parseInt(token));
        }
        // Otherwise, it must be an operator
        else {
            int val1 = st.pop();
            int val2 = st.pop();

            if (token.equals("+")) {
                st.push(val1 + val2);
            } else if (token.equals("-")) {
                st.push(val1 - val2);
            } else if (token.equals("*")) {
                st.push(val1 * val2);
            } else if (token.equals("/")) {
                st.push(floorDiv(val1, val2));
            } else if (token.equals("^")) {
                st.push((int)Math.pow(val1, val2));
            }
        }
    }
    return st.pop();
}

public static void main(String[] args) {
    String[] arr = {"+", "*", "/", "+", "100", "200", "2", "5", "7"};
    System.out.println(evaluatePrefix(arr));
}

}

Python

def evaluatePrefix(arr): st = [] n = len(arr)

# Traverse from right to left
for i in range(n - 1, -1, -1):
    token = arr[i]

    # If it's an operand (number), push it onto the stack
    if token[0].isdigit() or (len(token) > 1 and token[0] == '-'):
        st.append(int(token))

    # Otherwise, it must be an operator
    else:
        val1 = st.pop()
        val2 = st.pop()

        if token == "+":
            st.append(val1 + val2)
        elif token == "-":
            st.append(val1 - val2)
        elif token == "*":
            st.append(val1 * val2)
        elif token == "/":
            st.append(int(val1 // val2))
        elif token == "^":
            st.append(pow(val1, val2))

return st.pop()

if name == "main": arr = ["+", "*", "/", "+", "100", "200", "2", "5", "7"] print(evaluatePrefix(arr))

C#

using System; using System.Collections.Generic;

class GFG {

static int floorDiv(int a, int b) {
    if (a * b < 0 && a % b != 0)
        return (a / b) - 1;
    return a / b;
}

static int evaluatePrefix(string[] arr) {
    Stack<int> st = new Stack<int>();
    int n = arr.Length;

    // Traverse from right to left
    for (int i = n - 1; i >= 0; i--) {
        string token = arr[i];

        // If it's an operand (number), push it onto the stack
        if (Char.IsDigit(token[0]) || (token.Length > 1 && token[0] == '-')) {
            st.Push(int.Parse(token));
        }

        // Otherwise, it must be an operator
        else {
            int val1 = st.Pop();
            int val2 = st.Pop();

            if (token == "+") {
                st.Push(val1 + val2);
            } else if (token == "-") {
                st.Push(val1 - val2);
            } else if (token == "*") {
                st.Push(val1 * val2);
            } else if (token == "/") {
                st.Push(floorDiv(val1, val2));
            } else if (token == "^") {
                st.Push((int)Math.Pow(val1, val2));
            }
        }
    }
    return st.Pop();
}

static void Main() {
    string[] arr = { "+", "*", "/", "+", "100", "200", "2", "5", "7" };
    Console.WriteLine(evaluatePrefix(arr)); 
}

}

JavaScript

function evaluatePrefix(arr) { let st = []; let n = arr.length;

// Traverse from right to left
for (let i = n - 1; i >= 0; i--) {
    let token = arr[i];

    // If it's an operand (number), push it onto the stack
    if (!isNaN(token) && token.length > 0) {
        st.push(parseInt(token));
    }

    // Otherwise, it must be an operator
    else {
        let val1 = st.pop();
        let val2 = st.pop();

        if (token === "+") {
            st.push(val1 + val2);
        } else if (token === "-") {
            st.push(val1 - val2);
        } else if (token === "*") {
            st.push(val1 * val2);
        } else if (token === "/") {
            st.push(Math.floor(val1 / val2)); 
        } else if (token === "^") {
            st.push(Math.pow(val1, val2));
        }
    }
}
return st.pop();

}

// Driver code let arr = ["+", "*", "/", "+", "100", "200", "2", "5", "7"]; console.log(evaluatePrefix(arr));

`