Disk block writes with limited write cycles

0
Sign in

A storage device has n blocks with ids 0 to n - 1. Every block can be written at most max_cycles times; after that it is worn out and can never be written again.

Implement a DiskManager class:

  • DiskManager(n: int, max_cycles: int) creates the disk. Every block starts with max_cycles remaining write cycles.
  • write() -> int performs one write and returns the id of the block it used. Choose the block with the fewest remaining cycles among blocks that still have at least one. If several blocks tie, choose the smallest id. The chosen block loses one cycle. If every block is worn out, return -1.
  • replace(block_id: int) -> None swaps in a new physical block at block_id. Its remaining cycles reset to max_cycles.
  • remaining(block_id: int) -> int returns the block's remaining cycles.

Constraints

  • 0 <= n <= 10^5, 0 <= max_cycles <= 10^9
  • Up to 10^5 calls in total.
  • Every operation should run in better than O(n) time.

Example 1

disk = DiskManager(3, 2)
write() -> 0, write() -> 0, write() -> 1, write() -> 1,
write() -> 2, write() -> 2, write() -> -1

Once block 0 has been written it has fewer cycles than the untouched blocks, so it is chosen again until it is worn out.

Example 2

disk = DiskManager(3, 3)
write() -> 0, write() -> 0, write() -> 0, write() -> 1   # block 1 has 2 left
replace(0)                                               # block 0 back to 3
write() -> 1, write() -> 1                               # 2 and then 1 are fewer than 3
write() -> 0                                             # blocks 0 and 2 both have 3; 0 is smaller

Reconstructed from the reported question; details may differ from what interviewers ask.

AmazonCodingMedium

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.