Convert Nested Key-Value Pairs to YAML Format

viaGlassdoor

Problem: Given a list of slash-delimited key paths mapped to values (e.g., /web/leetcode/contest: 435), convert them into a nested YAML-formatted string, grouping shared path prefixes under common parent keys with proper indentation.

Constraints: Paths can share arbitrary-depth prefixes; output must nest children under the correct parent with consistent indentation (commonly 2 spaces per level).

Example: Input:

/web/leetcode/contest: 435
/web/leetcode/discuss: Zomato
/web/leetcode/premium/amount: 15000
/leetcode/explore: interviewExp
/leetcode/store: premium

Output:

web:
  leetcode:
    contest: 435
    discuss: Zomato
    premium:
      amount: 15000
leetcode:
  explore: interviewExp
  store: premium

Approach: Build a nested map (trie-like structure) by splitting each path on '/' and inserting the value at the final key, creating intermediate maps for each path segment as needed. Then recursively serialize the nested map to YAML, tracking indentation depth and printing key: for nested maps (indent += 2, recurse) or key: value for leaf values.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account