Skip to main content
ProductsDesktop toolsTASTECADDrawing reviewTASTEFILESFile managementTASTEFTPFile transferTASTESSHRemote workspaceTASTEZIPCompression and extractionTASTEWINMFile managementDeveloper toolsTASTECODERust integrated development environmentTASTESTUDIOIntegrated development and test environmentTASTEETLData integration (ETL)ServersTASTEREMOTERemote desktop serverTASTEGEOGeospatial serverTASTEMAILMail workspaceInvestingTASTESTOCKStock auto-trading desktop appGet startedDownloadsDocumentationBuyAll products
Marketplace
News
TechNewsToday's dev newsDeveloper docsProgramming languagesRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp & desktop frameworksTauriFlutterReact NativeElectronAlgorithmsAlgorithm basicsCore algorithmsAdvanced algorithmsPractical algorithms
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcaseCommunity guide
Work with usTech transferWebsite buildDesktop app buildRelease and payment pipelineSales partnerContact
ServicesRemote desktopCustom installer packages
TASTEDEV
Products

Desktop tools

TASTECADComplex drawings, opened with easeTASTEFILESJust the files you need, as fast as possibleTASTEFTPThe tidiest path for your filesTASTESSHA stronger link between you and your serversTASTEZIPPack faster, unpack saferTASTEWINMA keyboard-first file manager with two panes

Developer tools

TASTECODEEdit, build, debug and test Rust apps in one windowTASTESTUDIOFrom editing to remote tests and approved AI fixesTASTEETLMove data while you watch the values

Servers

TASTEREMOTEA remote desktop you run on your own serverTASTEGEORebuilding a GeoServer-compatible geospatial server in RustTASTEMAILTake back control of your email

Investing

TASTESTOCKStock auto-trading that follows the rules you set: when, and what

Get started

DownloadsLatest builds of every productDocsHow to use each productBuySubscriptions and perpetual licencesAll productsEvery product at a glance
All products
MarketplaceNews
Tech

News

Today's dev newsOfficial announcements on languages, frameworks, GitHub and AIDeveloper docsGuides to languages, frameworks and algorithms

Programming languages

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App & desktop frameworksTauriFlutterReact NativeElectron

Algorithms

Algorithm basicsComplexity analysis · Sorting · Searching · Basic data structures · Trees and heapsCore algorithmsGraph traversal · Shortest paths & minimum spanning trees · Dynamic programming · Greedy algorithms · Divide and conquer · BacktrackingAdvanced algorithmsString algorithms · Math and number theory · Bit manipulation · Segment trees · Union-findPractical algorithmsCoding interview strategy · LRU cache · Rate limiting · Consistent hashing
All development docs
Community
ProjectsDiscover builders and their workDevelopment logsDecisions and lessons learnedPromptsReusable instructionsAI tool issuesProblems and workarounds for Claude, Codex, GeminiShowcaseFinished resultsCommunity guideHow we build in the open
Work with us
Tech transferNative apps in Rust and eguiWebsite build10 languages, accounts, docs and downloadsDesktop app buildRust and egui, no WebViewRelease and payment pipelineSigning, MSI, deb, rpm, AppImage, hashesSales partnerRecommend us and earn 30%ContactBuilds, partnerships and investment
Services
Remote desktopReach your computer from a browserCustom installer packagesOnly the features you need, settings preloaded
Buy
EN
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Log in
Log in
TASTEDEV

From small tools to better development.

support@tastedev.netSupport TASTEDEV
ProductsProduct lineupBuyDocsDownloadsMarketplaceSupport
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcase
PoliciesAbout usPrivacy policyTerms of serviceSubscription termsRefund policyCommunity guidelines
AccountLog inSign up
Visitors
Today
Yesterday
Total views
Company
GXSOFT
Representative
CHOI YOUNG GU
Business registration number
853-44-00368
Address
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Phone
+82-10-4404-1523
Email
whitecalvin@tastedev.net
Privacy officer
CHOI YOUNG GU

© 2026 TASTEDEVProduct information is based on verified development sources.Released · improving

LRU cache docs
LRU cache
LRU Cache ConceptsHow an LRU Cache WorksImplementing an LRU CacheComplexity of an LRU CacheLRU Practice ProblemsLRU in the Real World
Discussions

LRU cache guide · 5/6

LRU Practice Problems

These four problems extend the basic LRU cache in directions that come up in interviews and in real code. Try each one before reading the approach. The solutions use OrderedDict to keep the focus on the idea; you can swap in the hand-written linked list from the implementation chapter.

Problem 1: Count the misses

A program issues a sequence of page requests, and memory holds k pages managed by LRU. Return the number of misses (page faults). Then find the smallest k for which the number of misses is at most a given limit.

Approach: simulate the cache once per capacity. Because LRU is a stack algorithm, misses never increase when k grows, so the smallest suitable k can be found with binary search over 1..number of distinct pages.

from collections import OrderedDict

def lru_misses(requests, k):
    cache, misses = OrderedDict(), 0
    for page in requests:
        if page in cache:
            cache.move_to_end(page)
        else:
            misses += 1
            cache[page] = True
            if len(cache) > k:
                cache.popitem(last=False)
    return misses

def smallest_capacity(requests, limit):
    lo, hi = 1, max(1, len(set(requests)))
    while lo < hi:
        mid = (lo + hi) // 2
        if lru_misses(requests, mid) <= limit:
            hi = mid
        else:
            lo = mid + 1
    return lo

reqs = [1, 2, 3, 1, 4, 1, 2, 5, 1, 2, 3, 4]
print(lru_misses(reqs, 3))         # 8
print(smallest_capacity(reqs, 7))  # 4

Problem 2: LRU with expiry

Extend the cache so that every entry also expires ttl seconds after it was written. An expired entry behaves like a missing one. The clock must be injectable so the cache can be tested without sleeping.

Approach: store (value, expires_at). Check the expiry on get and delete stale entries lazily. Capacity eviction still follows LRU order. Lazy expiry keeps both operations O(1); expired entries may occupy space until they are read or evicted, which is the same trade-off Redis makes alongside its active expiry cycle.

import time
from collections import OrderedDict

class TTLLRUCache:
    def __init__(self, capacity, ttl, clock=time.monotonic):
        self.capacity, self.ttl, self.clock = capacity, ttl, clock
        self.data = OrderedDict()            # key -> (value, expires_at)

    def get(self, key, default=None):
        item = self.data.get(key)
        if item is None:
            return default
        value, expires_at = item
        if self.clock() >= expires_at:
            del self.data[key]               # lazy expiry
            return default
        self.data.move_to_end(key)
        return value

    def put(self, key, value):
        self.data[key] = (value, self.clock() + self.ttl)
        self.data.move_to_end(key)
        if len(self.data) > self.capacity:
            self.data.popitem(last=False)

now = [0.0]
c = TTLLRUCache(2, ttl=10, clock=lambda: now[0])
c.put("a", 1)
now[0] = 5;  print(c.get("a"))   # 1
now[0] = 11; print(c.get("a"))   # None (expired)

Problem 3: Byte-limited cache

Entries have different sizes. The cache has a byte budget instead of an entry count. Inserting a value must evict least recently used entries until the new value fits. A value larger than the whole budget is not cached at all.

Approach: keep a running total of bytes. After an insert or update, pop from the least recent end while the total exceeds the budget. Each entry is evicted at most once after being inserted, so the cost is O(1) amortized per operation.

from collections import OrderedDict

class ByteLRU:
    def __init__(self, max_bytes):
        self.max_bytes, self.used = max_bytes, 0
        self.data = OrderedDict()            # key -> bytes

    def get(self, key):
        if key not in self.data:
            return None
        self.data.move_to_end(key)
        return self.data[key]

    def put(self, key, blob):
        if len(blob) > self.max_bytes:
            return False
        if key in self.data:
            self.used -= len(self.data.pop(key))
        self.data[key] = blob
        self.used += len(blob)
        while self.used > self.max_bytes:
            _, old = self.data.popitem(last=False)
            self.used -= len(old)
        return True

b = ByteLRU(10)
b.put("x", b"12345"); b.put("y", b"1234"); b.get("x")
b.put("z", b"123")              # 12 bytes: evicts "y"
print(list(b.data), b.used)     # ['x', 'z'] 8

Problem 4: Memoize with a recency limit

A recursive function counts paths in a grid where some cells are blocked. Memoize it with a bounded LRU cache and report the hit ratio. Then explain why maxsize that is too small slows the function down.

Approach: decorate the function with functools.lru_cache(maxsize=...) and read cache_info(). Recursion revisits recent subproblems, so even a modest cache helps, but when maxsize is smaller than the active frontier the cache thrashes and most calls miss.

from functools import lru_cache

BLOCKED = {(1, 1), (2, 3)}
ROWS, COLS = 6, 6

@lru_cache(maxsize=64)
def paths(r, c):
    if (r, c) in BLOCKED or r >= ROWS or c >= COLS:
        return 0
    if (r, c) == (ROWS - 1, COLS - 1):
        return 1
    return paths(r + 1, c) + paths(r, c + 1)

print(paths(0, 0))
info = paths.cache_info()
print(f"hit ratio {info.hits / (info.hits + info.misses):.2f}")

Summary

  • Simulation plus the stack property of LRU turns capacity planning into a binary search.
  • TTL, byte budgets and memoization are all small extensions of the same ordered map.
  • Always reason about what happens when an update, an oversized value or a tiny capacity arrives.
Questions about this chapter?
Previous chapterComplexity of an LRU CacheNext chapterLRU in the Real World

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.