{"id":7738,"date":"2025-07-10T14:26:26","date_gmt":"2025-07-10T08:56:26","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=7738"},"modified":"2025-07-10T14:53:07","modified_gmt":"2025-07-10T09:23:07","slug":"evaluate-reverse-polish-notation","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/evaluate-reverse-polish-notation\/","title":{"rendered":"Evaluate Reverse Polish Notation"},"content":{"rendered":"\n<!-- Evaluate Reverse Polish Notation -->\n<link\n    href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\"\n    rel=\"stylesheet\"\n\/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.min.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n  .wp_blog_theme {\n    --primary: #e58c32;\n    --secondary: #f8c291;\n    --light-bg: #fef9f4;\n    --text-dark: #2d2d2d;\n    --tab-radius: 12px;\n    --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n    --code-bg: #001f3f;\n    --code-text: #d4f1ff;\n  }\n\n  .wp_blog_container {\n    font-family: 'Segoe UI', sans-serif;\n    background: var(--light-bg);\n    margin: 0;\n    padding: 0;\n    color: var(--text-dark);\n  }\n    \/* Heading *\/\n    .wp_blog_main-heading {\n        text-align: center;\n        font-size: 2.4rem;\n        color: var(--primary);\n        margin-top: 2.5rem;\n        font-weight: bold;\n    }\n\n    \/* Explanation Card *\/\n    .wp_blog_explanation,\n    .wp_blog_code-tabs-container {\n        max-width: 940px;\n        margin: 2rem auto;\n        padding: 2rem;\n        background: white;\n        border-radius: var(--tab-radius);\n        box-shadow: var(--shadow);\n    }\n\n    \/* Text and Visuals *\/\n    .wp_blog_explanation h2 {\n        font-size: 1.4rem;\n        color: var(--primary);\n        margin-bottom: 0.5rem;\n    }\n    .wp_blog_explanation p,\n    .wp_blog_explanation li {\n        font-size: 1.05rem;\n        line-height: 1.7;\n        margin: 0.5rem 0;\n    }\n    .wp_blog_explanation code {\n        background: #fef9f4;\n        padding: 3px 6px;\n        border-radius: 4px;\n        font-family: \"Courier New\", monospace;\n    }\n    .wp_blog_explanation img {\n        max-width: 100%;\n        border-radius: var(--tab-radius);\n        margin-top: 1rem;\n        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);\n    }\n\n    \/* Tab Buttons *\/\n    .wp_blog_code-tabs-header {\n        display: flex;\n        flex-wrap: wrap;\n        gap: 0.5rem;\n        margin-bottom: 1rem;\n    }\n    .wp_blog_code-tab-button {\n        padding: 0.6rem 1.2rem;\n        border: 1px solid var(--primary);\n        background: white;\n        color: var(--primary);\n        border-radius: 50px;\n        font-weight: 600;\n        cursor: pointer;\n        transition: all 0.3s ease;\n    }\n    .wp_blog_code-tab-button:hover {\n        background: var(--secondary);\n    }\n    .wp_blog_code-tab-button.active {\n        background: var(--primary);\n        color: white;\n    }\n\n    \/* Code Content *\/\n    .wp_blog_code-tab-content {\n        display: none;\n        background: var(--code-bg);\n        border-radius: var(--tab-radius);\n    }\n    .wp_blog_code-tab-content.active {\n        display: block;\n    }\n    .wp_blog_code-tab-content pre {\n        margin: 0;\n        padding: 1.5rem;\n        font-size: 1rem;\n        overflow-x: auto;\n        background: var(--code-bg);\n        border-radius: var(--tab-radius);\n        color: var(--code-text);\n    }\n<\/style>\n\n<div class=\"wp_blog_container wp_blog_theme\">\n<h1 class=\"wp_blog_main-heading\"><\/h1>\n\n<div class=\"wp_blog_explanation\">\n    <h2>Problem Statement:<\/h2>\n    <p>\n       You are given an array of strings <code>tokens<\/code> that represents an arithmetic expression in a <strong style=\"color: rgb(65, 81, 187);\"><\/strong>Reverse Polish Notation<\/strong>.\n    <\/p>\n\n    <p>Evaluate the expression. Return an integer that represents the value of the expression.<\/p>\n    \n    <p><strong>Note<\/strong> that:<\/p>\n    <ul>\n        <li>The valid operators are <code>'+'<\/code>, <code>'-'<\/code>, <code>'*'<\/code>, and <code>'\/'<\/code> .<\/li>\n        <li>Each operand may be an integer or another expression.<\/li>\n        <li>The division between two integers always <strong>truncates toward zero<\/strong>.<\/li>\n        <li>There will not be any division by zero.<\/li>\n        <li>The input represents a valid arithmetic expression in a reverse polish notation.<\/li>\n        <li>The answer and all the intermediate calculations can be represented in a <strong>32-bit<\/strong> integer.<\/li>\n    <\/ul>\n\n    <h2>Examples:<\/h2>\n    <p><strong>Example 1:<\/strong><\/p>\n    <p><strong>Input:<\/strong><\/p>\n        <p>tokens = [&#8220;2&#8243;,&#8221;1&#8243;,&#8221;+&#8221;,&#8221;3&#8243;,&#8221;*&#8221;]<\/p>\n    <p><strong>Output:<\/strong><code>9<\/code><\/p>\n    <p><strong>Explanation<\/strong><\/p>\n    <p><code>((2 + 1) * 3) = 9<\/code><\/p>\n\n    <p><strong>Example 2:<\/strong><\/p>\n    <p><strong>Input:<\/strong><\/p>\n        <p>tokens = [&#8220;4&#8243;,&#8221;13&#8243;,&#8221;5&#8243;,&#8221;\/&#8221;,&#8221;+&#8221;]<\/p>\n    <p><strong>Output:<\/strong><code>6<\/code><\/p>\n    <p><strong>Explanation<\/strong><\/p>\n    <p><code>(4 + (13 \/ 5)) = 6<\/code><\/p>\n\n    <p><strong>Example 3:<\/strong><\/p>\n    <p><strong>Input:<\/strong><\/p>\n        <p>tokens = [&#8220;10&#8243;,&#8221;6&#8243;,&#8221;9&#8243;,&#8221;3&#8243;,&#8221;+&#8221;,&#8221;-11&#8243;,&#8221;*&#8221;,&#8221;\/&#8221;,&#8221;*&#8221;,&#8221;17&#8243;,&#8221;+&#8221;,&#8221;5&#8243;,&#8221;+&#8221;]<\/p>\n    <p><strong>Output:<\/strong><code>22<\/code><\/p>\n    <p><strong>Explanation<\/strong><\/p>\n    <p>\n        <pre>\n            ((10 * (6 \/ ((9 + 3) * -11))) + 17) + 5\n            = ((10 * (6 \/ (12 * -11))) + 17) + 5\n            = ((10 * (6 \/ -132)) + 17) + 5\n            = ((10 * 0) + 17) + 5\n            = (0 + 17) + 5\n            = 17 + 5\n            = 22\n        <\/pre>\n    <\/p>\n\n    <h2>Constraints:<\/h2>\n    <ul>\n        <li><code>1 <= tokens.length <= 10<sup>4<\/sup><\/code><\/li>\n        <li><code>tokens[i]<\/code> is either an operator: <code>\"+\"<\/code>, <code>\"-\"<\/code>, <code>\"*\"<\/code>, or <code>\"\/\"<\/code>, or an integer in the range <code>[-200, 200]<\/code>.<\/li>\n    <\/ul>\n\n    <h2>Approach:<\/h2>\n    <ul>\n        <li><strong>Initialize a stack<\/strong> to store operands.<\/li>\n        <li><strong>Define operator functions <\/strong>using a map:\n            <ul>\n                <li>Each key <code>(+, -, *, \/)<\/code> maps to a function that performs the respective operation on two numbers.<\/li>\n            <\/ul>\n        <\/li>\n\n        <li><strong>Loop through each token<\/strong> in the input array:\n            <ul>\n                <li>If the token is an <strong>operator<\/strong>:<\/li>\n                <ul>\n                    <li>Pop the top two values from the stack.<\/li>\n                    <li>Convert them to numbers and apply the operator function.<\/li>\n                    <li>Push the result back to the stack<\/li>\n                <\/ul>\n            <\/li>\n\n        <li>If the token is a <strong>number:<\/strong>\n            <ul>\n                    <li>Push it directly to the stack.<\/li>\n\n            <\/ul>\n        <\/li>\n\n        <li><strong>Return the final result<\/strong> by popping the last element from the stack and converting it to a number.<\/li>\n\n    <\/ul>\n\n    <h2>Visualisation:<\/h2>\n    <img decoding=\"async\"\n        src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/07\/Screenshot-2025-07-10-at-2.21.41\u202fPM.png\"\n        alt=\"stack\"\n    \/>\n                <h2>Time Complexity:<\/h2>\n                <li>\n                  <p><strong>Time Complexity = O(n)<\/strong> \n                <\/li> \n                <h2>Space Complexity:<\/h2>\n                <li>\n                  <p><strong>Space Complexity = O(n)<\/strong> \n                <\/p>\n                <\/li>\n\n<h2>Dry Run<\/h2> <div style=\"background: #f9f9f9; border-left: 4px solid var(--primary); padding: 1rem; border-radius: var(--tab-radius); margin: 1rem 0;\"> <p><strong>Input:<\/strong><\/p> <pre style=\"white-space: pre-wrap; background: #fff5ea; padding: 1rem; border-radius: 8px; overflow-x: auto;\"> arr = [\"2\", \"1\", \"+\", \"3\", \"*\"] <\/pre> <p><strong>State Transitions:<\/strong><\/p> <pre style=\"white-space: pre-wrap; background: #fff5ea; padding: 1rem; border-radius: 8px; overflow-x: auto;\"> Initialize: stack = []\ni = 0 \u2192 arr[0] = \"2\"\n\u2192 Not an operator \u2192 stack.push(\"2\") \u2192 stack = [\"2\"]\n\ni = 1 \u2192 arr[1] = \"1\"\n\u2192 Not an operator \u2192 stack.push(\"1\") \u2192 stack = [\"2\", \"1\"]\n\ni = 2 \u2192 arr[2] = \"+\"\n\u2192 Operator found\n\u2192 a = stack.pop() = \"1\"\n\u2192 b = stack.pop() = \"2\"\n\u2192 ans = map[\"+\"](1, 2) = 3\n\u2192 stack.push(3) \u2192 stack = [3]\n\ni = 3 \u2192 arr[3] = \"3\"\n\u2192 Not an operator \u2192 stack.push(\"3\") \u2192 stack = [3, \"3\"]\n\ni = 4 \u2192 arr[4] = \"\"\n\u2192 Operator found\n\u2192 a = stack.pop() = \"3\"\n\u2192 b = stack.pop() = 3\n\u2192 ans = map[\"\"](3, 3) = 9\n\u2192 stack.push(9) \u2192 stack = [9]\n<\/pre>\n\n<p><strong>Final Output:<\/strong> <code>9<\/code><\/p> <p><strong>Final State:<\/strong> <code>stack = []<\/code> (after popping result)<\/p> <\/div>\n<\/div>\n\n<div class=\"wp_blog_code-tabs-container\">\n    <div class=\"wp_blog_code-tabs-header\">\n        <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">\n            JavaScript\n        <\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n<pre><code class=\"language-javascript\">\nvar evalRPN = function(arr) {\n    let stack = [];\n    const map = {\n        \"+\": (a,b) => (b+a),\n        \"*\": (a,b) => (b*a),\n        \"-\": (a,b) => (b-a),\n        \"\/\": (a,b) => Math.trunc(b\/a),\n    };\n        for(let i=0; i < arr.length; i++){\n            if(map[arr[i]]) {\n                let a = stack.pop();\n                let b = stack.pop();\n                let ans = map[arr[i]](+a,+b);\n                stack.push(ans);\n            } else {\n                stack.push(arr[i]) \n            }\n        }\n    return Number(stack.pop());\n};\n<\/code>\n<\/pre>\n<\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n        <pre><code class=\"language-python\">\ndef evalRPN(arr):\n    stack = []\n    map = {\n        \"+\": lambda a, b: b + a,\n        \"-\": lambda a, b: b - a,\n        \"*\": lambda a, b: b * a,\n        \"\/\": lambda a, b: int(b \/ a)\n    }\n    for token in arr:\n        if token in map:\n            a = stack.pop()\n            b = stack.pop()\n            ans = map[token](a, b)\n            stack.append(ans)\n        else:\n            stack.append(int(token))\n    return stack.pop()\n    <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n        <pre><code class=\"language-java\">\nimport java.util.*;\npublic class Solution {\n    public int evalRPN(String[] arr) {\n        Stack<Integer> stack = new Stack<>();\n        Map<String, java.util.function.BiFunction<Integer, Integer, Integer>> map = new HashMap<>();\n        map.put(\"+\", (a, b) -> b + a);\n        map.put(\"-\", (a, b) -> b - a);\n        map.put(\"*\", (a, b) -> b * a);\n        map.put(\"\/\", (a, b) -> b \/ a);\n        for (int i = 0; i < arr.length; i++) {\n            if (map.containsKey(arr[i])) {\n                int a = stack.pop();\n                int b = stack.pop();\n                int ans = map.get(arr[i]).apply(a, b);\n                stack.push(ans);\n            } else {\n                stack.push(Integer.parseInt(arr[i]));\n            }\n        }\n        return stack.pop();\n    }\n}\n <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n        <pre><code class=\"language-cpp\">\n#include &lt;iostream&gt;\n#include &lt;stack&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;unordered_map&gt;\nusing namespace std;\n\nint evalRPN(vector<string>& arr) {\n    stack<int> stack;\n    unordered_map<string, function<int(int, int)>> map = {\n        {\"+\", [](int a, int b) { return b + a; }},\n        {\"*\", [](int a, int b) { return b * a; }},\n        {\"-\", [](int a, int b) { return b - a; }},\n        {\"\/\", [](int a, int b) { return b \/ a; }}\n    };\n\n    for (int i = 0; i < arr.size(); i++) {\n        if (map.count(arr[i])) {\n            int a = stack.top(); stack.pop();\n            int b = stack.top(); stack.pop();\n            int ans = map[arr[i]](a, b);\n            stack.push(ans);\n        } else {\n            stack.push(stoi(arr[i]));\n        }\n    }\n\n    return stack.top();\n}\n<\/code><\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n        <pre><code class=\"language-c\">\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\nint evalRPN(char** arr, int size) {\n    int stack[1000];\n    int top = -1;\n    for (int i = 0; i < size; i++) {\n        if (!strcmp(arr[i], \"+\") || !strcmp(arr[i], \"-\") || !strcmp(arr[i], \"*\") || !strcmp(arr[i], \"\/\")) {\n            int a = stack[top--];\n            int b = stack[top--];\n            int ans;\n            if (!strcmp(arr[i], \"+\")) ans = b + a;\n            else if (!strcmp(arr[i], \"-\")) ans = b - a;\n            else if (!strcmp(arr[i], \"*\")) ans = b * a;\n            else ans = b \/ a;\n            stack[++top] = ans;\n        } else {\n            stack[++top] = atoi(arr[i]);\n        }\n    }\n    return stack[top];\n}\n<\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n        <pre><code class=\"language-csharp\">\nusing System;\nusing System.Collections.Generic;\npublic class Solution {\n    public int EvalRPN(string[] arr) {\n        Stack<int> stack = new Stack<int>();\n        Dictionary<string, Func<int, int, int>> map = new Dictionary<string, Func<int, int, int>> {\n            { \"+\", (a, b) => b + a },\n            { \"-\", (a, b) => b - a },\n            { \"*\", (a, b) => b * a },\n            { \"\/\", (a, b) => b \/ a }\n        };\n        for (int i = 0; i < arr.Length; i++) {\n            if (map.ContainsKey(arr[i])) {\n                int a = stack.Pop();\n                int b = stack.Pop();\n                int ans = map[arr[i]](a, b);\n                stack.Push(ans);\n            } else {\n                stack.Push(int.Parse(arr[i]));\n            }\n        }\n        return stack.Pop();\n    }\n}\n  <\/code><\/pre>\n    <\/div>\n<\/div>\n<\/div>\n<script>\n    document.addEventListener(\"DOMContentLoaded\", () => {\n        const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n        const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n        buttons.forEach((button) => {\n            button.addEventListener(\"click\", () => {\n                const lang = button.getAttribute(\"data-lang\");\n                buttons.forEach((btn) => btn.classList.remove(\"active\"));\n                contents.forEach((content) =>\n                    content.classList.remove(\"active\")\n                );\n                button.classList.add(\"active\");\n                document\n                    .querySelector(\n                        `.wp_blog_code-tab-content[data-lang=\"${lang}\"]`\n                    )\n                    .classList.add(\"active\");\n            });\n        });\n    });\n<\/script>\n","protected":false},"excerpt":{"rendered":"<p>Problem Statement: You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation. Evaluate the expression. Return an integer that represents the value of the expression. Note that: The valid operators are &#8216;+&#8217;, &#8216;-&#8216;, &#8216;*&#8217;, and &#8216;\/&#8217; . Each operand may be an integer or another expression. The<\/p>\n","protected":false},"author":108,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[322,260,176,175,212,211,811,810,174,172,173],"tags":[],"class_list":["post-7738","post","type-post","status-publish","format-standard","category-algorithms-and-data-structures","category-c-c-plus-plus","category-csharp","category-cplusplus","category-code-optimization","category-data-structures","category-data-structures-and-algorithms","category-dsa","category-java","category-javascript","category-python"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7738","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/108"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=7738"}],"version-history":[{"count":3,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7738\/revisions"}],"predecessor-version":[{"id":7742,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7738\/revisions\/7742"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=7738"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=7738"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=7738"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}