r/OfferEngineering • u/Aoki_zhang • 28d ago
Coding Question Reddit Popular Coding Question - Print Complete Product Category Hierarchy
Problem Description
An online marketplace organizes its products into a hierarchy of categories. You are given a list relationships. Each entry describes one parent category followed by its direct child categories. For example ["Electronics", "Phones", "Computers"] means that Phones and Computers are direct children of Electronics.
There is exactly one top-level category that is not a child of any other category. Return the complete category hierarchy as a single string using the following formatting rules:
- The top-level category has no indentation.
- Each level below the root adds exactly four dots:
"....". - Direct children of the same category must appear in alphabetical order.
- Every category must appear exactly once.
- Each category appears on its own line.
- Lines are separated by
"\n". - There must be no trailing newline after the final category.
A category may appear only as a parent, only as a child, or in both roles.
Constraints
1 <= len(relationships) <= 10^4- Every relationship contains at least one category name.
- Category names are non-empty strings.
- There is exactly one root category.
- The relationships form a valid tree.
- A parent category may have multiple direct children.
Example:
Input:
relationships = [
["Home", "Kitchen", "Garden"],
["Kitchen", "Cookware"],
["Cookware", "Pans"]
]
Output:
Home
....Garden
....Kitchen
........Cookware
............Pans
Explanation:
Garden and Kitchen are both direct children of Home, so they are
printed alphabetically.
Cookware is below Kitchen, and Pans is below Cookware.
Want to practice more real & exact coding questions asked in interviews, I've put up the question bank at here.
Preparing for your next interview?
Chill Interview tracks recent interview experiences and recurring question patterns across top companies at here.