惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Securelist
C
Cybersecurity and Infrastructure Security Agency CISA
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Security Affairs
Hacker News: Ask HN
Hacker News: Ask HN
L
Lohrmann on Cybersecurity
PCI Perspectives
PCI Perspectives
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
Cyber Attacks, Cyber Crime and Cyber Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
MyScale Blog
MyScale Blog
月光博客
月光博客
W
WeLiveSecurity
T
Threat Research - Cisco Blogs
Martin Fowler
Martin Fowler
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Recorded Future
Recorded Future
The GitHub Blog
The GitHub Blog
Webroot Blog
Webroot Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
TaoSecurity Blog
TaoSecurity Blog
P
Proofpoint News Feed
Google DeepMind News
Google DeepMind News
F
Full Disclosure
U
Unit 42
Jina AI
Jina AI
博客园 - 司徒正美
阮一峰的网络日志
阮一峰的网络日志
L
LINUX DO - 最新话题
宝玉的分享
宝玉的分享
大猫的无限游戏
大猫的无限游戏
The Hacker News
The Hacker News
The Last Watchdog
The Last Watchdog
T
Troy Hunt's Blog
腾讯CDC
T
Threatpost
H
Hacker News: Front Page
P
Palo Alto Networks Blog
博客园 - 聂微东
Last Week in AI
Last Week in AI
有赞技术团队
有赞技术团队
Help Net Security
Help Net Security
L
LINUX DO - 热门话题
N
News and Events Feed by Topic
人人都是产品经理
人人都是产品经理
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Spread Privacy
Spread Privacy

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
LeetCode Solution: 146. LRU Cache
AussieCoder · 2026-05-18 · via DEV Community

AussieCoder

LRU Cache: Because Your Computer Has Commitment Issues (LeetCode 146)

Hello, fellow coders and aspiring digital hoarders! Today, we're diving into a LeetCode classic that’s as common in interviews as "tell me about yourself" – the LRU Cache. If you've ever wondered how your web browser remembers your favorite sites, or why some app data seems to magically stay while older stuff vanishes, you're about to find out!


The Problem: Your Computer's Short-Term Memory

Imagine you have a super-important, but very small, desk. You can only fit a capacity number of items on it. When you put a new item on the desk:

  1. If the item is already there, you just update its content and put it on top (making it shiny and new).
  2. If it's new, you add it to the desk.
  3. Crucially: If adding this new item means your desk is now overflowing, you must throw away the item you haven't touched in the longest time. We call this the "Least Recently Used" (LRU) item. Out with the old, in with the slightly less old, maybe!

When you get an item from the desk:

  1. If it's there, great! You pick it up, use it, and then put it back on top of the desk (making it the most recently used).
  2. If it's not there, well, that's just awkward. You return -1.

The catch? Both get and put operations must be ridiculously fast, specifically O(1) on average. Because nobody has time for slow memory.


Intuition: The "Aha!" Moment 💡

At first glance, this problem might seem like a digital version of "Simon Says" with extra steps. You need to:

  1. Find things fast: If you have key 10, you need to grab its value immediately. A plain list would mean searching through everything, which is O(N) – no good for our O(1) requirement. This screams Hash Map! A map (or unordered_map in C++) lets us look up a key and get its value in average O(1) time.

  2. Maintain order and recency: How do we know what's LRU or MRU? A simple array won't work, because moving items around in an array (to make something MRU) is also O(N). We need something where we can easily remove an item from the middle and add it to the end (or beginning) in O(1) time. This, my friends, is the job for a Doubly Linked List! With prev and next pointers, a node can be unlinked and relinked with constant pointer manipulations.

So, the "aha!" moment is realizing we need both of them. The Hash Map gives us O(1) access to any item by its key, and crucially, it will store a pointer to that item's location in our Doubly Linked List. The Doubly Linked List then maintains the usage order, making it trivial to identify the LRU item (the one at the tail) and move an item to the MRU position (the head).


Approach: The Dynamic Duo Strikes Back!

Our strategy is simple yet elegant, like a perfectly optimized pantry:

  1. The Dynamic Duo:

    • We'll use a std::unordered_map<int, ListNode*> (let's call it cacheMap) to map each key to its corresponding ListNode in our linked list. This gives us lightning-fast lookups (key -> node).
    • We'll use a Doubly Linked List to keep track of the access order. The head of our list will always point to the Most Recently Used (MRU) item, and the tail will point to the Least Recently Used (LRU) item. To simplify things, we'll use "dummy" head and tail nodes that don't store actual data. They just act as bookends, making insertions and deletions much cleaner.
  2. The ListNode Structure:
    Each node in our doubly linked list will be a struct ListNode containing:

    • key: The actual key stored.
    • value: The value associated with the key.
    • prev: A pointer to the previous node.
    • next: A pointer to the next node.
  3. Core Operations (deleteNode, insertNode):
    These are our utility belt items, doing the heavy lifting in O(1):

    • deleteNode(node): Takes a node and removes it from its current position in the linked list by updating its neighbors' prev and next pointers. Poof, gone!
    • insertNode(node): Takes a node and inserts it right after our dummy head node. This effectively makes it the new MRU item. "Welcome to the front row!"
  4. LRUCache(int capacity):

    • Initialize our cacheMap.
    • Create our dummy head and tail nodes.
    • Link head->next = tail and tail->prev = head. An empty list, ready for action!
  5. int get(int key):

    • "Is this key even VIP enough to be in our exclusive club?" Check cacheMap.
    • If key isn't found (cacheMap.find(key) == cacheMap.end()), return -1. "Nope, not found. Try harder next time!"
    • If found:
      • Retrieve the ListNode* using cacheMap[key].
      • "Found it! Now it's super popular, so move it to the front." Call deleteNode() on it to remove it from its old spot.
      • Call insertNode() on it to place it right after the head.
      • Return the node->value.
  6. void put(int key, int value):

    • "Does this key already have a reservation?" Check cacheMap.
    • If key is found:
      • Retrieve the ListNode* from cacheMap.
      • Update its value.
      • "Ah, you're back! Let's update your info and put you at the top." deleteNode() and insertNode() to refresh its MRU status.
    • If key is not found:
      • "New face! Welcome to the party. Let's add you." Create a new ListNode(key, value).
      • Add it to cacheMap: cacheMap[key] = newNode;.
      • insertNode(newNode) to make it MRU.
      • "Party's getting a bit crowded, isn't it?" Check if (cacheMap.size() > capacity):
        • "Time for some tough decisions. Who's the least social butterfly?" The LRU node is always tail->prev.
        • "Sorry, old friend, your time has come."
        • deleteNode(tail->prev) to remove it from the list.
        • cacheMap.erase(tail->prev->key) to remove it from the map.
        • delete tail->prev; to free up that memory (we're not running a charity!).

Code: The Grand Symphony of Pointers and Maps

#include <unordered_map> // For O(1) average time complexity lookup

// A simple structure for our doubly linked list nodes
struct ListNode {
    int key;
    int value; // Storing the value associated with the key
    ListNode *prev;
    ListNode *next;

    // Constructor: key, value, optional prev/next for convenience
    ListNode(int k, int v, ListNode* p = nullptr, ListNode* n = nullptr) 
        : key(k), value(v), prev(p), next(n) {}
};

class LRUCache {
private:
    std::unordered_map<int, ListNode*> cacheMap; // Maps key to its node in the list
    int capacity; // Maximum number of items the cache can hold
    ListNode *head; // Dummy head node for the doubly linked list
    ListNode *tail; // Dummy tail node for the doubly linked list

    // Helper to remove a node from its current position in the list
    void deleteNode(ListNode* node) {
        // "Hasta la vista, baby!" - The node bids adieu to its neighbors.
        node->prev->next = node->next;
        node->next->prev = node->prev;
    }

    // Helper to insert a node right after the head (making it the Most Recently Used)
    void insertNode(ListNode* node) {
        // "Making a grand entrance!" - The node proudly claims its spot at the front.
        node->next = head->next;
        node->prev = head;
        head->next->prev = node;
        head->next = node;
    }

public:
    LRUCache(int cap) {
        capacity = cap;
        // Initialize dummy head and tail nodes. Their key/value don't matter.
        // They simplify logic by always having valid 'prev'/'next' for real nodes.
        head = new ListNode(0, 0); 
        tail = new ListNode(0, 0);

        // Link the dummy nodes to each other initially
        head->next = tail;
        tail->prev = head;
    }

    // Destructor to prevent memory leaks, a good practice for C++
    // We allocated nodes with 'new', so we must 'delete' them.
    ~LRUCache() {
        ListNode* current = head;
        while (current != nullptr) {
            ListNode* next = current->next;
            delete current;
            current = next;
        }
    }

    int get(int key) {
        // "Is this key even VIP enough to be in our exclusive club?"
        if (cacheMap.find(key) == cacheMap.end()) {
            return -1; // "Nope, not found. Try harder next time!"
        }

        // Found it! Now it's the coolest kid on the block, move it to the front.
        ListNode* node = cacheMap[key];
        deleteNode(node);
        insertNode(node);
        return node->value; // Return the value, as requested.
    }

    void put(int key, int value) {
        // "Does this key already have a reservation?"
        if (cacheMap.find(key) != cacheMap.end()) {
            // "Ah, you're back! Let's update your info and put you at the top."
            ListNode* node = cacheMap[key];
            node->value = value; // Update the value
            deleteNode(node);
            insertNode(node);
        } else {
            // "New face! Welcome to the party. Let's add you."
            ListNode* newNode = new ListNode(key, value);
            cacheMap[key] = newNode;
            insertNode(newNode);

            // "Party's getting a bit crowded, isn't it?"
            if (cacheMap.size() > capacity) {
                // "Time for some tough decisions. Who's the least social butterfly?"
                // The LRU node is always the one just before the dummy tail.
                ListNode* lruNode = tail->prev;

                // "Sorry, old friend, your time has come." Evict!
                deleteNode(lruNode); // Remove from linked list
                cacheMap.erase(lruNode->key); // Remove from map
                delete lruNode; // And finally, free up that memory!
            }
        }
    }
};

Enter fullscreen mode Exit fullscreen mode


Time & Space Complexity Analysis

"Alright, enough fun, let's talk numbers!"

  • Time Complexity:

    • LRUCache(capacity): O(1). Just initializing a few pointers and our map. No heavy lifting.
    • get(key): O(1) on average.
      • Hash map lookup (cacheMap.find or []) is O(1) on average.
      • Our deleteNode and insertNode helpers are pure pointer manipulation, always O(1).
    • put(key, value): O(1) on average.
      • Hash map operations (lookup, insert, erase) are O(1) on average.
      • deleteNode and insertNode are O(1).
      • Checking capacity and evicting is also constant time.
  • Space Complexity:

    • O(capacity).
      • Our cacheMap stores up to capacity key -> ListNode* pairs.
      • Our doubly linked list stores up to capacity ListNode objects (plus the two dummy nodes).
    • Each ListNode uses constant space for key, value, prev, next.

"So, yes, we achieved that blazing-fast O(1) average time!"


Key Takeaways: The Secrets of the Cache Masters

  • The Power Couple: When you need fast lookups and ordered removals/insertions, a Hash Map combined with a Doubly Linked List is your go-to pattern. It's like the Batman and Robin of data structures!
  • Dummy Nodes are MVPs: Those head and tail sentinels might seem unnecessary, but they elegantly handle edge cases (empty list, single item) by ensuring prev and next pointers are always valid, saving you from null-pointer checks and messy conditional logic.
  • C++ and Memory: Don't forget that if you new something, you eventually need to delete it. Our destructor ~LRUCache() ensures we're not being a memory hoarder. In languages with garbage collection (like Java or Python), this isn't a manual step, but it's crucial for C++.
  • Thinking beyond simple arrays: Many "move to front" or "remove least X" problems often hint at linked lists or other dynamic structures.

I hope this deep dive into the LRU Cache was as enlightening as it was entertaining! May your caches be ever efficient and your evictions swift. Happy coding!


Submission Details:
Author Account: aaradhyanegi009
Time Published: 2026-05-18 00:48:35