Compare write-back vs write-through caches
Company: PayPal
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of caching policies and memory/storage hierarchy trade-offs, focusing on how write-back and write-through handle writes, coherence, durability, latency, bandwidth, dirty bits, write amplification, and power-loss risks.
Constraints
- 1 <= capacity <= 10^5
- 0 <= len(operations) <= 2 * 10^5
- Each operation is ('R', address) or ('W', address)
- 1 <= read_cost, write_cost <= 10^9
- Expected solution should run in O(n) time with O(capacity) extra space
Examples
Input: (2, [], 5, 10)
Expected Output: {'write_through': {'latency': 0, 'memory_writes': 0}, 'write_back': {'latency': 0, 'memory_writes': 0, 'dirty_lines': 0}}
Explanation: No operations means no latency, no memory writes, and no dirty lines.
Input: (2, [('W', 1), ('W', 1)], 5, 10)
Expected Output: {'write_through': {'latency': 27, 'memory_writes': 2}, 'write_back': {'latency': 7, 'memory_writes': 0, 'dirty_lines': 1}}
Explanation: Write-through writes to memory on both writes. Write-back loads block 1 once, then keeps it dirty in cache with no memory write yet.
Hints
- Use a hash map plus an order-aware structure so you can test membership, update recency, and evict the LRU block in O(1) average time.
- Both simulators share most of their logic. The key differences are what happens on a write hit and whether a dirty block generates a memory write when evicted.