Skip to the code
cf.
+25 XP

#348 Folder Sizes for a File Explorer

medium

A web file explorer shows every folder with its total size. The project arrives as nested JSON. A file is { "name": ..., "size": n }. A folder is { "name": ..., "children": [...] }, where children may be empty. The top item is always a folder.

Write folderSizes(root) that returns one [path, total] pair for every folder, where path is the folder names from the top down joined with / (the top folder's path is just its name), and total is the sum of the sizes of all files anywhere inside it. Sort the pairs by path using normal string order (<).

Example 1

Input: root = {"name":"app","children":[{"name":"index.js","size":10},{"name":"src","children":[{"name":"a.js","size":5},{"name":"b.js","size":7}]}]}
Output: [["app",22],["app/src",12]]

src holds 5 + 7 = 12, and app holds 10 + 12 = 22.

Example 2

Input: root = {"name":"empty","children":[]}
Output: [["empty",0]]

A folder with nothing in it has size 0.

Constraints

  • 1 <= number of items <= 10^4
  • 0 <= size <= 10^6
  • Names have no /, and sibling names are unique.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).