LeetCode Entry

150. Evaluate Reverse Polish Notation

30.01.2024 medium 2024 kotlin rust

Solve Reverse Polish Notation.

150. Evaluate Reverse Polish Notation medium blog post substack youtube image.png

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/488

Problem TLDR

Solve Reverse Polish Notation.

Intuition

Push to stack until operation met, then pop twice and do op.

Approach

Let’s try to be brief.

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(n)\)

Code


  fun evalRPN(tokens: Array<String>) = Stack<Int>().run {
    for (s in tokens) push(when (s) {
      "+" -> pop() + pop()
      "-" -> -pop() + pop()
      "*" -> pop() * pop()
      "/" -> pop().let { pop() / it }
      else -> s.toInt()
    })
    pop()
  }


  pub fn eval_rpn(tokens: Vec<String>) -> i32 {
    let mut s = vec![];
    for t in tokens { if let Ok(n) = t.parse() { s.push(n) }
     else { let (a, b) = (s.pop().unwrap(), s.pop().unwrap());
      s.push(match t.as_str() {
        "+" => a + b, "-" => b - a, "*" => a * b, _ => b / a }) }}
    s[0]
  }