We are given the total possible page numbers that can be referred to. We are also given a cache (or memory) size (The number of page frames that the cache can hold at a time). The LRU caching scheme is to remove the least recently used frame when the cache is full and a new page is referenced which is not there in the cache.

  • Both Map and Arrays are used in the implementation.
from typing import List, Dict
 
 
class LRUCache:
	def __init__(self, capacity: int):
		self.capacity = capacity
		self.cache = []
		self.map = {}
 
	# This function returns false if key is not
	# present in cache. Else it moves the key to
	# front by first removing it and then adding
	# it, and returns true.
	def get(self, key: int) -> bool:
		if key not in self.map:
			return False
		self.cache.remove(key)
		self.cache.append(key)
		return True
 
	# this method is also known as refer
	def getOrSet(self, key: int) -> None:
		if self.get(key):
			return
		self.put(key)
 
	# displays contents of cache in Reverse Order
	def display(self) -> None:
		for i in range(len(self.cache)-1, -1, -1):
			print(self.cache[i], end=" ")
 
	def put(self, key: int) -> None:
		if len(self.cache) == self.capacity:
			first_key = self.cache.pop(0)
			del self.map[first_key]
		self.cache.append(key)
		self.map[key] = len(self.cache) - 1
 
 
if __name__ == '__main__':
	cache = LRUCache(4)
	cache.refer(1)
	cache.refer(2)
	cache.refer(3)
	cache.refer(1)
	cache.refer(4)
	cache.refer(5)
	cache.display()
 

Attempt

'''
#gyan_pelo 
 
'''