Giter Site home page Giter Site logo

lru_cache's Introduction

lru_cache

Implementing LRU Cache using C#

Creating the boilerplate using .NET5 CLI -

mkdir src
mkdir tests

cd src
dotnet new classlib -o LRU_Cache

cd ../tests
dotnet new xunit -o LRU_Cache.Tests

cd ..
dotnet new sln

dotnet sln add .\src\LRU_Cache\
dotnet sln add .\tests\LRU_Cache.Tests\

I am using 2 collections to implement the cache -

  1. Dictionary<K, CacheItem<K, V>> The dictionary serves as a lookup for retreiving values from the cache in O(1) constant time

  2. LinkedList<CacheItem<K, V>> The doubly linked list serves as a tracking list to track least used items, items which are least used are evicted from the front according to the LRU policy.


The cache is initialized with a positive capacity.

It provides 2 methods.

  1. Get(K key) Gets the value from the cache, shifts the item which is fetched at last, if no matching key is found it returns default(V).

  2. Put(K key, V value) Sets the value into both the dictionary lookup and the tracking list in the end, if the tracking lists' count is equal to the capacity then the first item from the front of the tracking list is evicted and the new item is pushed into the item.


Space Complexity
O(n) because of the extra auxillary tracking list.

Time Complexity

  • Fetching key - O(1)
  • Setting key - Average case O(1), if reaches capacity then O(n)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.