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 · 2/6

How an LRU Cache Works

An LRU cache has to answer two questions quickly: "is this key in the cache?" and "which key was used least recently?". No single classic data structure answers both in constant time, so the standard design combines two: a hash map for lookup and a doubly linked list for recency order. This chapter walks through that design and traces it on a small example.

Two structures working together

  • The hash map maps each key to its node in the list, so finding an entry is O(1) on average.
  • The doubly linked list keeps the entries in recency order. The front (next to head) is the most recently used entry; the back (next to tail) is the least recently used.
  • Each node stores its key as well as its value. On eviction we only have the node at the back, and we need its key to delete it from the map.
  • The list is doubly linked because removing a node from the middle needs its predecessor. With prev and next pointers, unlinking takes O(1).
  • Two sentinel nodes, head and tail, never hold data. They remove every special case for an empty list or for the first and last node.
head <-> [C] <-> [B] <-> [A] <-> tail
         most recent      least recent

map: { A: node A, B: node B, C: node C }

The operations

A get(key) looks the key up in the map. On a miss it returns a sentinel value such as -1 or None. On a hit it unlinks the node and inserts it right after head, then returns the value.

A put(key, value) first checks the map. If the key exists, it updates the value and moves the node to the front, exactly like a hit. Otherwise, if the cache is full, it removes the node just before tail and deletes that node's key from the map; then it creates a new node, inserts it after head and stores it in the map.

All pointer work reduces to two helpers. Each touches a constant number of pointers, which is why both operations are O(1).

def unlink(node):
    # A <-> node <-> B  becomes  A <-> B
    node.prev.next = node.next
    node.next.prev = node.prev

def push_front(head, node):
    # head <-> X  becomes  head <-> node <-> X
    node.prev = head
    node.next = head.next
    head.next.prev = node
    head.next = node

Moving a node to the front is simply unlink(node) followed by push_front(head, node). Evicting is unlink(tail.prev) plus a map deletion.

A trace with capacity 3

The list is written from most recent to least recent.

StepOperationResultList after the stepNote
1put(A, 1)-Ainsert
2put(B, 2)-B, Ainsert
3put(C, 3)-C, B, Acache is now full
4get(A)1A, C, Bhit: A moves to the front
5put(D, 4)-D, A, Cfull: B is evicted
6get(B)-1D, A, Cmiss: order unchanged
7put(C, 30)-C, D, Aupdate: C moves to the front
8put(E, 5)-E, C, Dfull: A is evicted
9get(D)4D, E, Chit

Step 5 is the key moment. A was inserted first, so a FIFO cache would have evicted it. Because step 4 read A, LRU evicts B instead. Step 6 shows that a miss changes nothing, and step 7 shows that an update counts as a use.

Reproducing the trace

The quickest way to check a trace is a short simulation with OrderedDict, which already provides the two primitives we need: move_to_end and popitem(last=False).

from collections import OrderedDict

def run(capacity, ops):
    cache = OrderedDict()            # first = least recent, last = most recent
    for op, key, *value in ops:
        result = "-"
        if op == "get":
            if key in cache:
                cache.move_to_end(key)
                result = cache[key]
            else:
                result = -1
        else:
            if key in cache:
                cache.move_to_end(key)
            elif len(cache) >= capacity:
                cache.popitem(last=False)
            cache[key] = value[0]
        order = ", ".join(reversed(cache))  # most recent first
        print(f"{op}({key}) -> {result}: {order}")

run(3, [("put", "A", 1), ("put", "B", 2), ("put", "C", 3), ("get", "A"),
        ("put", "D", 4), ("get", "B"), ("put", "C", 30), ("put", "E", 5), ("get", "D")])

The last printed line is get(D) -> 4: D, E, C, matching the table.

Common mistakes in the walkthrough

  • Forgetting to move the node on a get. The cache then behaves like FIFO.
  • Forgetting to move the node when put updates an existing key.
  • Evicting before checking whether the key already exists. Updating a key in a full cache must not evict anything.
  • Removing the node from the list but not from the map (or the reverse). The two structures must always describe the same set of keys.

Summary

  • The map gives O(1) lookup; the doubly linked list gives O(1) reordering and eviction.
  • Sentinels head and tail remove edge cases; nodes keep their key so eviction can clean up the map.
  • Hits and updates move an entry to the front; misses change nothing; eviction removes the node before tail.
Questions about this chapter?
Previous chapterLRU Cache ConceptsNext chapterImplementing an LRU Cache

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.