Construct Binary Tree S-Expression
Updated
Problem statement
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), omitting empty children. 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:
E1: Invalid input string.E2: Duplicate pair.E3: A parent has more than two children.E4: Multiple roots.E5: Cycle in the tree.
Function
validateBinaryTree(pairs: String) → String Complete validateBinaryTree.
String pairs: a space-separated list of parent-child pairs
Returns String: either an S-expression or an error code.
Examples
Example 1
pairs = "(A,B) (B,C) (A,D)"return = "(A(B(C))(D))"The pairs form a valid tree rooted at A.
Example 2
pairs = "(A,B) (A,B)"return = "E2"The pair (A,B) appears twice.
Constraints
- 1 <= pairs.length <= 10^5
- Node labels are uppercase English letters in the visible examples; hidden tests may use the same token format.
More Optiver Online Assessment questions
- Chance a Die Game Balance Reaches ZeroOA · Seen Dec 2026
- Chance a Hand of Cards Multiplies to More Than a ThresholdOA · Seen Dec 2026
- Chance a Sum of Random Draws Has a Given Number of DigitsOA · Seen Dec 2026
- Expected Draws to Remove All Green CountersOA · Seen Dec 2026
- Expected Profit of a Doubling Betting SystemOA · Seen Dec 2026
- Expected Steps Until a Random Walk Gets Far From ZeroOA · Seen Dec 2026
- Rolling Until One Face's Own Total Passes a ThresholdOA · Seen Dec 2026
- Two Ranked Teams Meeting in a Random BracketOA · Seen Dec 2026
- Overheat Prevention ControllerOA · Seen Nov 2026
- Power Cell BankOA · Seen Nov 2026
Similar questions at other companies
- Count Parent Nodes With a Target SumAdobe · OAAdobe interview questions
- Render a Task Tree from CSV RowsStripe · PHONE SCREEN · ONSITE INTERVIEWStripe interview questions
- Match a Descendant Selector in a DOM TreeMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- N-Ary Tree Codec OperationsLinkedIn · ONSITE INTERVIEWLinkedIn interview questions
- Recover a Tree from Preorder Depth EncodingSuperhuman · PHONE SCREENSuperhuman interview questions
- Count Prime Values in SubtreesVisa · OAVisa interview questions
- Part 1: The Narrowest KeyScale AI · OAScale AI interview questions
- Sewer Drainage PartitionTwo Sigma · OATwo Sigma interview questions
- Merge Row Trees by Key PathHudson River Trading · OAHudson River Trading interview questions
- Count Balanced Nodes in a Rooted TreeDRW · OADRW interview questions