FastPrepSimplify a Binary Expression Tree
Problems/Simplify a Binary Expression Tree

Simplify a Binary Expression Tree

Amazon logoAmazon● MediumFULLTIMEONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The interview report establishes the task identity and central capability. This practice contract supplies only the portable interface, deterministic boundary rules, and output serialization needed for consistent execution.

A valid binary expression tree is serialized in prefix order. Each token is +, -, *, a variable name, or a signed integer.

Simplify the tree bottom-up. Fold an operator when both children are integers. Also apply x + 0 = x, 0 + x = x, x - 0 = x, x * 1 = x, 1 * x = x, and x * 0 = 0. Return the simplified tree as one space-separated prefix expression.

Function

simplifyExpressionTree(preorder: String[]) → String

Examples

Example 1

preorder = ["+","*","x","1","0"]return = "x"

Multiplication by one and addition of zero both disappear.

Example 2

preorder = ["*","+","2","3","y"]return = "* 5 y"

The constant addition folds while the variable multiplication remains.

Constraints

  • 1 <= preorder.length <= 10000.
  • The prefix sequence is a valid binary expression tree.
  • Every folded result fits in a signed 64-bit integer.

More Amazon problems

  • Count Adjacent Symbol Pairs for BPEONSITE INTERVIEW · Seen Nov 2026
  • First Non-Repeating CharacterOA · ONSITE INTERVIEW · Seen Nov 2026
  • Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
See Amazon hiring insights
Saved
class Solution {
    public String simplifyExpressionTree(String[] preorder) {
      // write your code here
    }
}
Checking account…