Folder Size Ledger
Medium · design
A cloud drive keeps a ledger of how many bytes its files take up. Files live in folders, and a path such as /music/rock/song.mp3 starts with / and lists the folders on the way, separated by /, ending with the name of the file. The drive starts empty. You are given three lists of the same length describing operations: operations[i] is "write", "remove" or "usage", paths[i] is a path, and sizes[i] is a size in bytes (for a "remove" or "usage" it is 0 and should be ignored).
"write"stores a file ofsizes[i]bytes at the path. Folders on the way that do not exist yet are created. If a file is already stored at that path, it is replaced."remove"deletes whatever is at the path: a single file, or a folder together with everything inside it. If nothing is there, nothing happens."usage"asks for the total size in bytes of whatever is at the path: the size of a file, or the sum of all files inside a folder, however deep. If nothing is there, the answer is0.
A path is never used both for a file and as a folder on the way to another file. Names are compared exactly, so /ab and /abc are different folders.
Return a list with the answer to every "usage", in the order they appear.
Examples
Example 1
Input: operations = ["write", "write", "usage", "write", "usage", "remove", "usage"], paths = ["/docs/a.txt", "/docs/img/b.png", "/docs", "/docs/a.txt", "/docs", "/docs/img", "/docs"], sizes = [10, 25, 0, 4, 0, 0, 0]
Output: [35, 29, 4]
The folder /docs holds 10 + 25 bytes. Writing /docs/a.txt again replaces the 10 with 4, giving 29. Removing /docs/img takes away 25 bytes, leaving 4.
Example 2
Input: operations = ["usage", "write", "usage", "usage", "usage"], paths = ["/x", "/ab/f", "/ab/f", "/abc", "/ab/g"], sizes = [0, 7, 0, 0, 0]
Output: [0, 7, 0, 0]
The first path does not exist yet, so its usage is 0. A file path answers with its own size. /abc and /ab/g were never written, so they use 0 bytes.
Constraints
- 1 <= len(operations) <= 5 * 10^4
- len(paths) == len(sizes) == len(operations)
- operations[i] is write, remove or usage
- Each path starts with / and has between 1 and 8 names, each 1 to 10 characters long made of lower-case letters, digits and dots
- 0 <= sizes[i] <= 10^9