FastPrepLRU Cache with Hit and Miss Counters
Problem · Design

LRU Cache with Hit and Miss Counters

Learn this problem
MediumLinkedIn logoLinkedInFULLTIMEONSITE INTERVIEW

Problem statement

Simulate a least-recently-used cache of string keys and values. Process commands PUT key value and GET key. A successful GET returns HIT value and makes that key most recently used; a missing GET returns MISS. Updating a key also makes it most recently used. An insertion beyond capacity evicts the least recently used key. After all commands, append STATS hits misses rate, where rate is hits divided by all GET operations and rounded to exactly three decimal places using round half up: an exact halfway value rounds upward. Return 0.000 when there were no GET operations.

Function

runLruWithCounters(capacity: int, operations: String[]) → String[]

Examples

Example 1

capacity = 2operations = ["PUT a 10","PUT b 20","GET a","PUT c 30","GET b","GET c"]return = ["HIT 10","MISS","HIT 30","STATS 2 1 0.667"]

Reading a makes b least recently used, so inserting c evicts b.

Example 2

capacity = 1operations = ["PUT x old","PUT x new","GET x"]return = ["HIT new","STATS 1 0 1.000"]

Updating x replaces its value without creating a second entry.

Constraints

  • 1 <= capacity <= 100000
  • 0 <= operations.length <= 200000
  • Each command is exactly PUT key value or GET key.
  • Keys and values are nonempty ASCII tokens without whitespace.

More LinkedIn problems

drafts saved locally
public String[] runLruWithCounters(int capacity, String[] operations) {
    // Write your code here.
}
capacity2
operations["PUT a 10","PUT b 20","GET a","PUT c 30","GET b","GET c"]
expected["HIT 10", "MISS", "HIT 30", "STATS 2 1 0.667"]
checking account