Datadog questions

Total File Size

DatadogEasy

A file system is modelled as a tree of entries. Each entry is a dictionary of one of two kinds:

  • a file: {"type": "file", "size": n}, where n is its size in bytes;
  • a directory: {"type": "dir", "children": [...]}, where children is a list of entries and may be empty.

A directory's children list may contain both files and other directories, nested to any depth. A directory has no size of its own. A file's size is its size field.

Part 1: Sum of file sizes

You are given an entry, a file or directory in the tree described above.

Return the total size in bytes of all files in entry and its descendants. A file's total is its own size. A directory's total is the sum of the sizes of all files anywhere beneath it, at any depth. An empty directory's total is 0.

  1. Example 1
    entry
    {"type":"dir","children":[{"size":100,"type":"file"},{"size":200,"type":"file"}]}
    Output
    300

    Why: The directory contains two files of 100 and 200 bytes and nothing else, so the total is 300.

  2. Example 2
    entry
    {"size":500,"type":"file"}
    Output
    500

    Why: A file has no children, so its total is just its own size.

  3. Example 3
    entry
    {"type":"dir","children":[{"size":10,"type":"file"},{"type":"dir","children":[{"size":40,"type":"file"},{"type":"dir","children":[{"size":5,"type":"file"}]}]}]}
    Output
    55

    Why: The top directory holds a file of 10 bytes and a nested directory. That nested directory holds a file of 40 bytes and a deeper directory holding a file of 5 bytes, so the total is 10 + 40 + 5 = 55.

Constraints

  • The tree rooted at entry has at least 1 and at most 10^5 entries
  • The nesting depth of entry is at most 500
  • For every file, 0 <= size <= 10^9
  • Every directory has a children list; a file has no children
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question