Binary Tree S-Expression Validation

Company: Optiver

Difficulty: medium

Problem Statement

Binary Tree S-Expression Validation Problem Description You are given a string containing parent-child pairs for a binary tree. Each pair is formatted like `(A,B)`, meaning `A` is the parent of `B`. If the pairs form a valid binary tree, return its S-expression. A node is rendered as `(value leftSubtree rightSubtree)` with no separators between the three parts and with empty children omitted, so a leaf `X` is rendered as `(X)`. When a node has two children, render them in lexicographic order by node label. If the input is invalid, return the highest-priority error code, where `E1` has the highest priority and `E5` the lowest: 1. `E1`: Invalid input string. 2. `E2`: Duplicate pair. 3. `E3`: A parent has more than two children. 4. `E4`: Multiple roots. 5. `E5`: Cycle in the tree. Exactly one code is returned: the first one in that list that applies to the input. Input Format The input is a single line containing the string `pairs`. The line is taken exactly as it is, including any spaces