Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    A category tree as an indented outline

    MediumAbout 25 minFull AccessLearn it: When to use recursion and when to prefer a loop

    The task

    An online shop stores its product categories as flat rows: an id, the id of the parent category (null for a top-level category) and a name. The admin page shows them as an indented outline.

    Complete Outline((int Id, int? ParentId, string Name)[] rows). Return one line per category, depth first: a category, then all of its children and their children, each level indented by two more spaces than its parent. Top-level categories, and the children of one parent, come in ascending id order. Throw ArgumentException when an id is used twice or a parent id belongs to no row. Throw InvalidOperationException when some rows cannot be reached from a top-level category, because they form a loop. The array is never null.

    Signature

    public static List<string> Outline((int Id, int? ParentId, string Name)[] rows)

    Examples

    • [(1, null, "Electronics"), (2, 1, "Laptops"), (3, 1, "Phones"), (4, 2, "Gaming"), (5, null, "Books")] → ["Electronics", " Laptops", " Gaming", " Phones", "Books"]. Gaming is a child of Laptops, so it comes before Phones, two spaces further in.
    • [(30, 10, "c"), (10, null, "a"), (20, 10, "b"), (5, null, "z")] → ["z", "a", " b", " c"]. Order is by id, not by input order or name.

    Limits: Up to 200,000 rows, nested up to 500 levels deep.

    The tests check: no rows, one row, top-level order, a whole shop, children by id, a chain of 500 levels, a missing parent, a repeated id, rows in a loop, a row that is its own parent, and 200,000 categories in time.

    Hints

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      public static class Solution
      {
          // One line per category, depth first; top-level categories and siblings by ascending id; two spaces per level.
          public static List<string> Outline((int Id, int? ParentId, string Name)[] rows)
          {
              throw new NotImplementedException();
          }
      }

      This problem comes with TechInterviewNotes Full Access

      Unlock all paid content on TechInterviewNotes.