1681. Well-Formed Postfix

Easy1.5 points estimatedStackStringArray

A calculator receives its input as a list of string tokens in postfix order. Each token is either one of the four binary operators +, -, *, / or an integer written in decimal, such as "12" or "-5". A token that is exactly "-" is the subtraction operator, while "-5" is an integer.

Return true if tokens form a valid postfix expression: every operator must find at least two operands waiting when it appears, consuming two and producing one, and exactly one value must remain at the end. Nothing is evaluated, so division by zero is irrelevant. Track only the current stack depth to solve it in O(n) time and O(1) extra space. Constraints: 1 <= tokens.length <= 1000 and every integer lies in [-1000, 1000].

Example 1

Input:
tokens = ["5","1","2","+","4","*","+","3","-"]
Output:
true
Explanation:

Depth goes 1,2,3,2,3,2,1,2,1 and never drops below the operands an operator needs, ending at 1.

Example 2

Input:
tokens = ["3","+"]
Output:
false
Explanation:

The operator finds only one operand.

Example 3

Input:
tokens = ["1","2"]
Output:
false
Explanation:

Two values remain on the stack at the end.

Constraints

1 ≤ tokens.length ≤ 1000; each token is "+", "-", "*", "/" or an integer string in [-1000, 1000] (a lone "-" is the operator)

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…