Quick Overview

Parse a string of parent-child pairs, check it for binary tree errors such as too many children, repeated edges, cycles, multiple roots and malformed input, and return either the right error code or the tree's S-expression. It tests string parsing, directed cycle detection, error priority rules and recursive tree serialization.

Build a tree from parent-child pairs and return its S-expression or an error code

Company: Goldman Sachs

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

You are given a string `nodes` that lists parent-child pairs in the form `(A,B)(B,C)(D,E)...`. Each node is a single uppercase letter, and a pair `(X,Y)` means that `X` is the parent of `Y`. Build the tree these pairs describe and return its **S-expression**. The S-expression of a tree is defined recursively. A leaf node `X` is written `(X)`. A node `X` with children is written as `(X`, followed by the S-expressions of its children in lexicographic order, followed by `)`. For a node with two children that is `(X(L...)(R...))`. If the input is invalid, return one of the following error codes instead. When more than one applies, the smallest code wins. - `E1`: some node has more than 2 children. - `E2`: a duplicate edge. - `E3`: a cycle is present. - `E4`: multiple roots. - `E5`: any other error, for example a node with multiple parents, a disconnected graph, or malformed input. ### Function Signature ```python def s_expression(nodes: str) -> str: ``` ### Rules - A pair is exactly five characters, `(X,Y)`, where `X` and `Y` are uppercase letters and there are no spaces inside. Pairs may be separated by any number of spaces, including none, and the string may start or end with spaces. - Parse first. If the string is not a sequence of such pairs, or holds no pair at all, return `E5`. The checks for `E1` to `E5` apply only to input that parses. - The nodes are the letters that appear in at least one pair. A root is a node that never appears as a child. - `E1` counts distinct children. A repeated pair adds its child once. - `E2` means the same ordered pair `(X,Y)` appears two or more times. `(A,B)` and `(B,A)` are different pairs. - A cycle is a directed cycle over the edges. A self-loop such as `(A,A)` is a cycle. - Return an error as the two-character string, for example `"E3"`. ### Constraints - `1 <= len(nodes) <= 10^4` - Each node is a single uppercase letter from `'A'` to `'Z'`. - `nodes` contains only `'('`, `')'`, `','`, uppercase letters and spaces. ### Examples ```text Input: nodes = "(A,B) (A,C) (B,D) (D,E)" Output: "(A(B(D(E)))(C))" ``` A is the root with children B and C. B has the single child D and D has the single child E, so B's subtree is `(B(D(E)))`, and C is the leaf `(C)`. ```text Input: nodes = "(A,B) (A,C) (A,D)" Output: "E1" ``` Node A has three children. ```text Input: nodes = "(A,B) (A,C) (A,B) (C,A)" Output: "E2" ``` A has only two distinct children, B and C, so `E1` does not apply. The pair `(A,B)` appears twice, and `E2` outranks the cycle A to C to A, which would give `E3`.

Overview: Parse a string of parent-child pairs, check it for binary tree errors such as too many children, repeated edges, cycles, multiple roots and malformed input, and return either the right error code or the tree's S-expression. It tests string parsing, directed cycle detection, error priority rules and recursive tree serialization.

You are given a string `nodes` that lists parent-child pairs in the form `(A,B)(B,C)(D,E)...`. Each node is a single uppercase letter, and a pair `(X,Y)` means that `X` is the parent of `Y`. Build the tree these pairs describe and return its S-expression. The S-expression of a tree is defined recursively. A leaf node `X` is written `(X)`. A node `X` with children is written as `(X`, followed by the S-expressions of its children in lexicographic order, followed by `)`. For a node with two children that is `(X(L...)(R...))`. Each child is a distinct single letter, so this is the alphabetical order of the child letters. If the input is invalid, return one of the following error codes instead. When more than one applies, the smallest code wins. - `E1`: some node has more than 2 children. - `E2`: a duplicate edge. - `E3`: a cycle is present. - `E4`: multiple roots. - `E5`: any other error, for example a node with multiple parents, a disconnected graph, or malformed input. ### Rules - A pair is exactly five characters, `(X,Y)`, where `X` and `Y` are uppercase letters and there are no spaces inside. Pairs may be separated by any number of spaces, including none, and the string may start or end with spaces. - Parse first. If the string is not a sequence of such pairs, or holds no pair at all, return `E5`. The checks for `E1` to `E5` apply only to input that parses. - The nodes are the letters that appear in at least one pair. A root is a node that never appears as a child. - `E1` counts distinct children. A repeated pair adds its child once. - `E2` means the same ordered pair `(X,Y)` appears two or more times. `(A,B)` and `(B,A)` are different pairs. - A cycle is a directed cycle over the edges. A self-loop such as `(A,A)` is a cycle. - Return an error as the two-character string, for example `"E3"`. ### Examples ```text Input: nodes = "(A,B) (A,C) (B,D) (D,E)" Output: "(A(B(D(E)))(C))" ``` A is the root with children B and C. B has the single child D and D has the single child E, so B's subtree is `(B(D(E)))`, and C is the leaf `(C)`. ```text Input: nodes = "(A,B) (A,C) (A,B) (C,A)" Output: "E2" ``` A has only two distinct children, B and C, so `E1` does not apply. The pair `(A,B)` appears twice, and `E2` outranks the cycle A to C to A, which would give `E3`. ### Constraints - `1 <= len(nodes) <= 10^4` - Each node is a single uppercase letter from `'A'` to `'Z'`. - `nodes` contains only `'('`, `')'`, `','`, uppercase letters and spaces.

Constraints

  • 1 <= len(nodes) <= 10^4
  • Each node is a single uppercase letter from 'A' to 'Z'.
  • nodes contains only '(', ')', ',', uppercase letters and spaces.

Examples

Input: ('(A,B)',)

Expected Output: '(A(B))'

Explanation: Single pair, the smallest valid tree: root A with the leaf B.

Input: (' ',)

Expected Output: 'E5'

Explanation: Three spaces and no pair, so parsing finds nothing and the answer is E5.

Hints

  1. Check the format of the whole string before building anything: one malformed spot anywhere, or no pair at all, makes the answer E5.
  2. Test the error conditions in the order E1, E2, E3, E4, E5 and return the first one that holds.
  3. E1 counts distinct children and E2 looks for a repeated ordered pair, so remember which pairs you have already seen. There are at most 26 nodes.

S-Expression from Parent-Child Pairs

mediumGoldman SachsSoftware Engineer

You are given a string nodes that lists parent-child pairs in the form (A,B)(B,C)(D,E).... Each node is a single uppercase letter, and a pair (X,Y) means that X is the parent of Y. Build the tree these pairs describe and return its S-expression.

The S-expression of a tree is defined recursively. A leaf node X is written (X). A node X with children is written as (X, followed by the S-expressions of its children in lexicographic order, followed by ). For a node with two children that is (X(L...)(R...)). Each child is a distinct single letter, so this is the alphabetical order of the child letters.

If the input is invalid, return one of the following error codes instead. When more than one applies, the smallest code wins.

  • E1: some node has more than 2 children.
  • E2: a duplicate edge.
  • E3: a cycle is present.
  • E4: multiple roots.
  • E5: any other error, for example a node with multiple parents, a disconnected graph, or malformed input.

Rules

  • A pair is exactly five characters, (X,Y), where X and Y are uppercase letters and there are no spaces inside. Pairs may be separated by any number of spaces, including none, and the string may start or end with spaces.
  • Parse first. If the string is not a sequence of such pairs, or holds no pair at all, return E5. The checks for E1 to E5 apply only to input that parses.
  • The nodes are the letters that appear in at least one pair. A root is a node that never appears as a child.
  • E1 counts distinct children. A repeated pair adds its child once.
  • E2 means the same ordered pair (X,Y) appears two or more times. (A,B) and (B,A) are different pairs.
  • A cycle is a directed cycle over the edges. A self-loop such as (A,A) is a cycle.
  • Return an error as the two-character string, for example "E3".

Examples

Input: nodes = "(A,B) (A,C) (B,D) (D,E)"
Output: "(A(B(D(E)))(C))"

A is the root with children B and C. B has the single child D and D has the single child E, so B's subtree is (B(D(E))), and C is the leaf (C).

Input: nodes = "(A,B) (A,C) (A,B) (C,A)"
Output: "E2"

A has only two distinct children, B and C, so E1 does not apply. The pair (A,B) appears twice, and E2 outranks the cycle A to C to A, which would give E3.

Constraints

  • 1 <= len(nodes) <= 10^4
  • Each node is a single uppercase letter from 'A' to 'Z'.
  • nodes contains only '(', ')', ',', uppercase letters and spaces.

Examples

Example 1
Input
('(A,B)',)
Output
'(A(B))'
Notes
Single pair, the smallest valid tree: root A with the leaf B.
Example 2
Input
(' ',)
Output
'E5'
Notes
Three spaces and no pair, so parsing finds nothing and the answer is E5.

Constraints

  • •1 <= len(nodes) <= 10^4
  • •Each node is a single uppercase letter from 'A' to 'Z'.
  • •nodes contains only '(', ')', ',', uppercase letters and spaces.

Comments (0)

No comments yet. Be the first to comment!

Submit your answer

Approved first answer today earns 30 XP
Bold⌘BItalic⌘IInline code⌘`Bullet listTab to nest (○ ■)Numbered listTab to nest (a. i.)QuoteCode block
Formatting help
Signature
def s_expression(nodes) -> str:
Sample call
s_expression('(A,B)')
Language
Case 1
Input
('(A,B)',)
Expected
'(A(B))'
Case 2
Input
('   ',)
Expected
'E5'

Browse More Questions

Show the approach

Approach

Scan nodes once from left to right. A space is skipped. Any other position must start a five-character pair: '(', an uppercase letter, ',', an uppercase letter and ')'. If it does not, or the scan ends without finding a pair, the answer is E5 before any graph check runs, which is the parse-first rule. During the scan each letter is marked as a node, and a 26 by 26 table records which ordered pairs have been seen. The first time a pair (X,Y) appears, X's distinct-child count and Y's parent count each go up by one. A later copy of the same pair only sets a duplicate flag, so every count is over distinct edges.

The checks then run in the order E1, E2, E3, E4, E5, so the first one that holds is the smallest applicable code. E1 holds when some distinct-child count exceeds 2. E2 holds when the duplicate flag is set. For E3, peel the graph in topological order (Kahn's algorithm): start from every node with no parent, and each time a node is removed, lower the remaining parent count of each of its children, adding a child to the work list when its count reaches zero. Every node is removed exactly when the distinct edges contain no directed cycle. A self-loop (A,A) keeps A's count at 1 forever, so it is reported as a cycle too. E4 holds when more than one node has no parent. With no cycle at least one node has no parent, so past E4 there is exactly one root. E5 then holds when some node has two or more parents.

If no code fires, every node except the root has exactly one parent, and following parents upward from any node never repeats a node and must stop at the single root. The pairs therefore form one connected tree. A disconnected graph has either a cycle or a second root, so it has already returned an earlier code. The answer is built recursively from the root by scanning the root's row of the edge table from 'A' to 'Z', then each child's row in the same way. Each child's S-expression starts with '(' followed by its own distinct letter, so letter order equals lexicographic order of the children's S-expressions. The tree has at most 26 nodes, so the recursion stays shallow.

Edge cases: an all-space string or a string with no valid pair returns E5; one malformed spot anywhere returns E5 even after valid pairs; a self-loop returns E3; a pair repeated on a node with two distinct children returns E2, because E1 counts distinct children; two roots that share a child return E4, which outranks the multiple-parent E5.

Time complexity:
O(n)
Space complexity:
O(1)