← Questions

Recent file tracker with date and insertion order

0
MicrosoftCoding

Implement a FileStorageSystem class that records files and answers two kinds of listing queries.

  • store_file(file: str, date: str) -> None records a file with its storage date, given as "yyyy-MM-dd". If the same file name is stored again, its date is replaced with the new one.
  • get_kth_recent_files(k: int) -> list[str] returns the names of the k most recently stored files, newest date first. Files with the same date are ordered alphabetically by name. If fewer than k files exist, return all of them.
  • return_all_files() -> list[str] returns every stored file name in the order it was first inserted.

Constraints: up to 10^5 calls in total; names are non-empty strings; dates are valid calendar dates. Aim for queries that do not re-sort all files each time.

Example

fs = FileStorageSystem()
fs.store_file("notes.txt", "2024-03-01")
fs.store_file("budget.xlsx", "2024-05-10")
fs.store_file("alpha.md", "2024-05-10")
fs.store_file("old.log", "2023-12-31")

fs.get_kth_recent_files(3)   # ["alpha.md", "budget.xlsx", "notes.txt"]
fs.get_kth_recent_files(10)  # ["alpha.md", "budget.xlsx", "notes.txt", "old.log"]
fs.return_all_files()        # ["notes.txt", "budget.xlsx", "alpha.md", "old.log"]

Example 2 (re-storing a file)

fs.store_file("old.log", "2024-06-01")
fs.get_kth_recent_files(2)   # ["old.log", "alpha.md"]
fs.return_all_files()        # unchanged: insertion order keeps the first store

Clarifying questions

  • When a file is re-stored with an older date, should its date still be replaced?
  • Is k <= 0 possible, and should it return an empty list?
  • How often are queries called compared with stores?
  • Can I compare dates as strings, since yyyy-MM-dd sorts the same as the date?

What a strong answer covers

  • Keeps a dict from name to date plus an insertion-ordered list (or Python's ordered dict) for return_all_files, which re-storing does not change.
  • Keeps a sorted structure keyed by (date descending, name ascending), for example a SortedList of (negated date, name), removing the old key on re-store: O(log n) per store, O(k) per query.
  • Compares ISO dates as strings safely, and orders ties by name.
  • Handles k larger than the file count and a file re-stored with a newer or older date.
  • Tests both examples, ties on the same date, and repeated re-stores of one file.

Follow-ups

  • Delete a file.
  • List files stored in a date range.
  • Make queries return only files stored on or after a given date, paginated.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding