• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to secondary sidebar

GoHired

Interview Questions asked in Google, Microsoft, Amazon

Join WeekEnd Online Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

  • Home
  • Best Java Books
  • Algorithm
  • Internship
  • Certificates
  • About Us
  • Contact Us
  • Privacy Policy
  • Array
  • Stack
  • Queue
  • LinkedList
  • DP
  • Strings
  • Tree
  • Mathametical
  • Puzzles
  • Graph

Implement LRU Cache

August 27, 2014 by Dhaval Dave

Generally Interviewer can ask you simply to implement LRU cache, first explain which data structure you will use and why.
Its well known coding question being asked by all Tech giants like Amazon , Flipkart, Microsoft.
LRU (Least Recently Used) Cache holds Page numbers which are recently used and throws out old or least recently used page number or entries.

For LRU Important fenomenon is “aging”.
When a page is referenced, it will be “young” (latest) and if its not referenced/called its will be “old”.
If a page is moderately old and get referenced, its young again.
So Entries in LRU Cache goes to and fro frequently.
Q1) Which kind of data structure is good for this ?
Array ? Stack ? Queue ? Link List ???  Obviously Link List.
As with just movement of two pointer we can move any node(which contains page number ) to and fro easily.
Q2) Which data structure will be useful to implement new and old referenced page number(node)
Array? Stack ? Queue ??? Queue is Answer right
So to implement LRU Cache we can use Queue implemented with Linked List.
Q3) How can we search efficiently that one page is referenced is in queue already?

Every time search queue in O(n) ?
Better Approch is to use Hash which stores page number which are in queue.
so DS used : Queue with LL and Hash
Sample code we have compiled and put

#include<iostream>
#include<map>
 
using namespace std;
 
struct node
{
  int pg;
  struct node *next, *prev;
};
 
class LRUCache
{
  int size;
  int MAXSZ;
  struct node *head,*tail;
  public:
  LRUCache(int maxsize){
    MAXSZ=maxsize;
    size=0;
    head=new node();
    tail=new node();
    head->pg= tail->pg=-1;
    head->next= tail;
    head->prev= tail->next= NULL;
    tail->prev= head;
  }
 
  map<int, struct node *> m;
  void add_to_head(node * );
  void remove_from_list(node *);
 
  public:
  void get();
  void put (int pgno);
};
void LRUCache::add_to_head(struct node *n){
  n->next= head->next;
  n->prev= head;
  n->next->prev= n;
  head->next= n;
}
 
void LRUCache::remove_from_list(node *n){
  if (size==0)
    return;
  n->prev->next= n->next;
  n->next->prev= n->prev;
}
 
void LRUCache::put(int pgno){
  if (m.find(pgno)==m.end()){
    if (size >= MAXSZ)
    {
      m.erase(tail->prev->pg);
      remove_from_list(tail->prev);
    }
    else size++;
    struct node *nn = new node();
    nn->pg=pgno;
    add_to_head(nn);
    m.insert(make_pair(pgno,nn));
  }
  else{
    struct node *n= m[pgno];
    remove_from_list(n);
    add_to_head(n);
  }
}
void LRUCache::get(){
  struct node *temp=head;
  while (temp!=NULL){
    cout << temp->pg << " ";
    temp=temp->next;
  }
  cout << endl;
}
 
int main(){
 
  LRUCache lru(3); //specify size
  lru.get();
  lru.put(1);
  lru.put(2);
  lru.get();
  lru.put(1);
  lru.get();
  lru.put(3);
  lru.get();
  lru.put(4);
  lru.get();
 
  return 0;
 
}
You can see Working code Here : http://ideone.com/DFql9R

Similar Articles

Filed Under: Adobe Interview Questions, Amazon Interview Question, Flipkart Interview Questions, Interview Questions, Microsoft Interview Questions, problem Tagged With: Array, Hashmap, Linked List, Queue, Stack

Reader Interactions

Primary Sidebar

Join WeekEnd Online/Offline Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

Join WeekEnd Online/Offline Batch from 4-April-2020

WhatsApp us

Secondary Sidebar

Custom Search

  • How I cracked AMAZON
  • LeetCode
  • Adobe
  • Amazon
  • Facebook
  • Microsoft
  • Hacker Earth
  • CSE Interview

Top Rated Questions

1014 Practice Question of New GRE – Princeton

Amazon Interview On-Campus For Internship – 1

N teams are participating. each team plays twice with all other teams. Some of them will go to the semi final. Find Minimum and Maximum number of matches that a team has to win to qualify for finals ?

Check a String is SUBSEQUENCE of another String Find Minimum length for that ( DNA Matching )

robot standing at first cell of an M*N matrix. It can move only in two directions, right and down. In how many ways, it can reach to the last cell i.e. (M, N) Code it

Find the smallest window in a string containing all characters of another string

Practo Hiring Experience

C++ OOPs Part1

Inorder and Preorder traversals of a Binary Tree given. Output the Postorder traversal of it.

TicTacToe Game As Asked in Flipkart

Maximum difference between two elements s.t larger element appears after the smaller number

K’th Largest Element in BST when modification to BST is not allowed

SAP Off Campus Hiring_ March 2015 Sample Questions

Linked List V/S Binary Search Tree

Edit Distance ( Dynamic Programming )

Length of the longest substring without repeating characters

SAP Off Campus Hiring_ March 2015 Verbal Skills

Printing intermediate Integers between one element & next element of array

Memory Efficient LinkedList

Find Percentage of Words matching in Two Strings

Minimum insertions to form a palindrome

C++ OOPs Part2

Print all nodes that are at distance k from a leaf node

Get Minimum element in O(1) from input numbers or Stack

C Program for TAIL command of UNIX

25 horses 5 tracks Find 3 fastest puzzle

N Petrol bunks or City arranged in circle. You have Fuel and distance between petrol bunks. Is it possible to find starting point so that we can travel all Petrol Bunks

Subset Sum Problem Dynamic programming

How strtok() Works

Find two non repeating elements in an array of repeating elements

Copyright © 2025 · Genesis Framework · WordPress · Log in