Buffer-pool LRU simulation

A free medium coding practice problem from databases. Solve it in JavaScript, TypeScript or Python and check your solution against fresh hidden tests — edge cases and random inputs — as often as you like.

Difficulty
Medium
Type
Function
Topic
Databases
Languages
JavaScript, TypeScript or Python

Problem

A database buffer pool caches up to capacity pages and evicts the LEAST RECENTLY USED page when it must load a page and is full. Replay the page accesses in pages (integers) starting from an empty pool: an access is a HIT if the page is cached (it becomes the most recently used), otherwise a MISS (the page is loaded and becomes most recently used, evicting the LRU page first if the pool is full). With capacity = 0 nothing is ever cached.

Return [hits, misses]. 0 ≤ capacity ≤ 100 000, up to 100 000 accesses — each access must be O(1).

Function signature

// JavaScript
function lruHitsMisses(capacity, pages)

// TypeScript
function lruHitsMisses(capacity: any, pages: any): any

// Python
def lru_hits_misses(capacity, pages):

Examples

  1. lruHitsMisses(2, [1,2,1,3,2,1]) → [1,5]
  2. lruHitsMisses(3, [1,2,3,4,1,2,5,1,2,3,4,5]) → [2,10]

How checking works

Run your code against the examples above, then submit a check: it runs on the server against hidden tests built fresh each time, including edge cases and random inputs. Practice is untimed and never affects a verified score; when you are ready, take a graded coding challenge to earn a badge.

More practice problems

Next steps