LRU Cache Implementation - GeeksforGeeks

CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems




WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


ML & Data Science
                        


Machine Learning

Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


School Learning
                        


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


DSA Live Classes


System Design


Java Backend Development


Full Stack LIVE


Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


DSA- Self Paced


SDE Theory


Must-Do Coding Questions


Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Competitive Programming


Data Structures with C++


Data Science


Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


DSA- Self Paced


CIP


JAVA / Python / C++


Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


School Guide


Python Programming


Learn To Make Apps


Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Searching Algorithms


Sorting Algorithms


Graph Algorithms


Pattern Searching


Geometric Algorithms


Mathematical


Bitwise Algorithms


Randomized Algorithms


Greedy Algorithms


Dynamic Programming


Divide and Conquer


Backtracking


Branch and Bound


All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Asymptotic Analysis


Worst, Average and Best Cases


Asymptotic Notations


Little o and little omega notations


Lower and Upper Bound Theory


Analysis of Loops


Solving Recurrences


Amortized Analysis


What does 'Space Complexity' mean ?


Pseudo-polynomial Algorithms


Polynomial Time Approximation Scheme


A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Arrays


Linked List


Stack


Queue


Binary Tree


Binary Search Tree


Heap


Hashing


Graph


Advanced Data Structure


Matrix


Strings


All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Company Preparation


Top Topics


Practice Company Questions


Interview Experiences


Experienced Interviews


Internship Interviews


Competititve Programming


Design Patterns


System Design Tutorial


Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


C


C++


Java


Python


C#


JavaScript


jQuery


SQL


PHP


Scala


Perl


Go Language


HTML


CSS


Kotlin


ML & Data Science
                        


Machine Learning

Data Science


Machine Learning


Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


Mathematics


Operating System


DBMS


Computer Networks


Computer Organization and Architecture


Theory of Computation


Compiler Design


Digital Logic


Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


GATE Computer Science Notes


Last Minute Notes


GATE CS Solved Papers


GATE CS Original Papers and Official Keys


GATE 2021 Dates


GATE CS 2021 Syllabus


Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


HTML


CSS


JavaScript


AngularJS


ReactJS


NodeJS


Bootstrap


jQuery


PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


Software Design Patterns


System Design Tutorial


School Learning
                        


School Programming


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Number System


Algebra


Trigonometry


Statistics


Probability


Geometry


Mensuration


Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


ISRO CS Original Papers and Official Keys


ISRO CS Solved Papers


ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


UGC NET CS Notes Paper II


UGC NET CS Notes Paper III


UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Campus Ambassador Program


School Ambassador Program


Project


Geek of the Month


Campus Geek of the Month


Placement Course


Competititve Programming


Testimonials


Student Chapter


Geek on the Top


Internship


Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Top 50 Array Problems


Top 50 String Problems


Top 50 Tree Problems


Top 50 Graph Problems


Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Apply for Jobs


Post a Job


JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


All DSA Problems


Problem of the Day


Interview Series: Weekly Contests


Bi-Wizard Coding: School Contests


Contests and Events


Practice SDE Sheet

GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Data StructuresArrayIntroduction to ArraysArrays in C/C++Arrays in JavaProgram for array rotationReversal algorithm for array rotationBlock swap algorithm for array rotationRearrange an array such that arr[i] = iWrite a program to reverse an array or stringRearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < iLinked ListLinked List | Set 1 (Introduction)Linked List vs ArrayLinked List | Set 2 (Inserting a node)Linked List | Set 3 (Deleting a node)Delete a Linked List node at a given positionCircular Linked List | Set 1 (Introduction and Applications)Circular Linked List | Set 2 (Traversal)Split a Circular Linked List into two halvesSorted insert for circular linked listStackStack Data Structure (Introduction and Program)Stack in C++ STLStack Class in JavaStack in PythonC# Stack with ExamplesQueue using StacksDesign and Implement Special Stack Data Structure | Added Space Optimized VersionImplement two stacks in an arrayImplement Stack using QueuesQueueQueue | Set 1 (Introduction and Array Implementation)Applications of Queue Data StructurePriority Queue | Set 1 (Introduction)Applications of Priority QueueDeque | Set 1 (Introduction and Applications)LRU Cache ImplementationQueue – Linked List ImplementationBinary TreeBinary Tree | Set 1 (Introduction)Binary Tree | Set 2 (Properties)Binary Tree | Set 3 (Types of Binary Tree)Tree Traversals (Inorder, Preorder and Postorder)Inorder Tree Traversal without RecursionInorder Tree Traversal without recursion and without stack!Construct Tree from given Inorder and Preorder traversalsConstruct a tree from Inorder and Level order traversals | Set 1Construct Complete Binary Tree from its Linked List RepresentationBinary Search TreeBinary Search Tree | Set 1 (Search and Insertion)Binary Search Tree | Set 2 (Delete)Advantages of BST over Hash TableConstruct BST from given preorder traversal | Set 1Construct BST from given preorder traversal | Set 2Binary Tree to Binary Search Tree ConversionSorted Linked List to Balanced BSTSorted Array to Balanced BSTFind the node with minimum value in a Binary Search TreeHeapBinary HeapTime Complexity of building a heapApplications of Heap Data StructureBinomial HeapFibonacci Heap | Set 1 (Introduction)Leftist Tree / Leftist HeapK-ary HeapHeapSortIterative HeapSortHashingHashing | Set 1 (Introduction)Index Mapping (or Trivial Hashing) with negatives allowedHashing | Set 2 (Separate Chaining)Hashing | Set 3 (Open Addressing)Double HashingPrint a Binary Tree in Vertical Order | Set 2 (Map based Method)Find whether an array is subset of another array | Added Method 5Union and Intersection of two linked lists | Set-3 (Hashing)Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)GraphGraph and its representationsBreadth First Search or BFS for a GraphDepth First Search or DFS for a GraphDetect Cycle in a Directed GraphDetect cycle in an undirected graphDetect Cycle in a directed graph using colorsTopological SortingAll Topological Sorts of a Directed Acyclic GraphKahn’s algorithm for Topological SortingMatrixRotate Matrix ElementsInplace rotate square matrix by 90 degrees | Set 1Rotate a matrix by 90 degree without using any extra space | Set 2Rotate a Matrix by 180 degreeRotate each ring of matrix anticlockwise by K elementsTurn an image by 90 degreeCheck if all rows of a matrix are circular rotations of each otherSort the given matrixFind the row with maximum number of 1sFind median in row wise sorted matrixAdvanced Data StructureMemory efficient doubly linked listXOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2Memory efficient doubly linked listXOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
Introduction to Arrays
Arrays in C/C++
Arrays in Java
Program for array rotation
Reversal algorithm for array rotation
Block swap algorithm for array rotation
Rearrange an array such that arr[i] = i
Write a program to reverse an array or string
Rearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < i
Linked List | Set 1 (Introduction)
Linked List vs Array
Linked List | Set 2 (Inserting a node)
Linked List | Set 3 (Deleting a node)
Delete a Linked List node at a given position
Circular Linked List | Set 1 (Introduction and Applications)
Circular Linked List | Set 2 (Traversal)
Split a Circular Linked List into two halves
Sorted insert for circular linked list
Stack Data Structure (Introduction and Program)
Stack in C++ STL
Stack Class in Java
Stack in Python
C# Stack with Examples
Queue using Stacks
Design and Implement Special Stack Data Structure | Added Space Optimized Version
Implement two stacks in an array
Implement Stack using Queues
Queue | Set 1 (Introduction and Array Implementation)
Applications of Queue Data Structure
Priority Queue | Set 1 (Introduction)
Applications of Priority Queue
Deque | Set 1 (Introduction and Applications)
LRU Cache Implementation
Queue – Linked List Implementation
Binary Tree | Set 1 (Introduction)
Binary Tree | Set 2 (Properties)
Binary Tree | Set 3 (Types of Binary Tree)
Tree Traversals (Inorder, Preorder and Postorder)
Inorder Tree Traversal without Recursion
Inorder Tree Traversal without recursion and without stack!
Construct Tree from given Inorder and Preorder traversals
Construct a tree from Inorder and Level order traversals | Set 1
Construct Complete Binary Tree from its Linked List Representation
Binary Search Tree | Set 1 (Search and Insertion)
Binary Search Tree | Set 2 (Delete)
Advantages of BST over Hash Table
Construct BST from given preorder traversal | Set 1
Construct BST from given preorder traversal | Set 2
Binary Tree to Binary Search Tree Conversion
Sorted Linked List to Balanced BST
Sorted Array to Balanced BST
Find the node with minimum value in a Binary Search Tree
Binary Heap
Time Complexity of building a heap
Applications of Heap Data Structure
Binomial Heap
Fibonacci Heap | Set 1 (Introduction)
Leftist Tree / Leftist Heap
K-ary Heap
HeapSort
Iterative HeapSort
Hashing | Set 1 (Introduction)
Index Mapping (or Trivial Hashing) with negatives allowed
Hashing | Set 2 (Separate Chaining)
Hashing | Set 3 (Open Addressing)
Double Hashing
Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
Find whether an array is subset of another array | Added Method 5
Union and Intersection of two linked lists | Set-3 (Hashing)
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Graph and its representations
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Detect Cycle in a Directed Graph
Detect cycle in an undirected graph
Detect Cycle in a directed graph using colors
Topological Sorting
All Topological Sorts of a Directed Acyclic Graph
Kahn’s algorithm for Topological Sorting
Rotate Matrix Elements
Inplace rotate square matrix by 90 degrees | Set 1
Rotate a matrix by 90 degree without using any extra space | Set 2
Rotate a Matrix by 180 degree
Rotate each ring of matrix anticlockwise by K elements
Turn an image by 90 degree
Check if all rows of a matrix are circular rotations of each other
Sort the given matrix
Find the row with maximum number of 1s
Find median in row wise sorted matrix
Memory efficient doubly linked list
XOR Linked List – A Memory Efficient Doubly Linked List | Set 1
XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
Memory efficient doubly linked list
XOR Linked List – A Memory Efficient Doubly Linked List | Set 1
XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
Data StructuresArrayIntroduction to ArraysArrays in C/C++Arrays in JavaProgram for array rotationReversal algorithm for array rotationBlock swap algorithm for array rotationRearrange an array such that arr[i] = iWrite a program to reverse an array or stringRearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < iLinked ListLinked List | Set 1 (Introduction)Linked List vs ArrayLinked List | Set 2 (Inserting a node)Linked List | Set 3 (Deleting a node)Delete a Linked List node at a given positionCircular Linked List | Set 1 (Introduction and Applications)Circular Linked List | Set 2 (Traversal)Split a Circular Linked List into two halvesSorted insert for circular linked listStackStack Data Structure (Introduction and Program)Stack in C++ STLStack Class in JavaStack in PythonC# Stack with ExamplesQueue using StacksDesign and Implement Special Stack Data Structure | Added Space Optimized VersionImplement two stacks in an arrayImplement Stack using QueuesQueueQueue | Set 1 (Introduction and Array Implementation)Applications of Queue Data StructurePriority Queue | Set 1 (Introduction)Applications of Priority QueueDeque | Set 1 (Introduction and Applications)LRU Cache ImplementationQueue – Linked List ImplementationBinary TreeBinary Tree | Set 1 (Introduction)Binary Tree | Set 2 (Properties)Binary Tree | Set 3 (Types of Binary Tree)Tree Traversals (Inorder, Preorder and Postorder)Inorder Tree Traversal without RecursionInorder Tree Traversal without recursion and without stack!Construct Tree from given Inorder and Preorder traversalsConstruct a tree from Inorder and Level order traversals | Set 1Construct Complete Binary Tree from its Linked List RepresentationBinary Search TreeBinary Search Tree | Set 1 (Search and Insertion)Binary Search Tree | Set 2 (Delete)Advantages of BST over Hash TableConstruct BST from given preorder traversal | Set 1Construct BST from given preorder traversal | Set 2Binary Tree to Binary Search Tree ConversionSorted Linked List to Balanced BSTSorted Array to Balanced BSTFind the node with minimum value in a Binary Search TreeHeapBinary HeapTime Complexity of building a heapApplications of Heap Data StructureBinomial HeapFibonacci Heap | Set 1 (Introduction)Leftist Tree / Leftist HeapK-ary HeapHeapSortIterative HeapSortHashingHashing | Set 1 (Introduction)Index Mapping (or Trivial Hashing) with negatives allowedHashing | Set 2 (Separate Chaining)Hashing | Set 3 (Open Addressing)Double HashingPrint a Binary Tree in Vertical Order | Set 2 (Map based Method)Find whether an array is subset of another array | Added Method 5Union and Intersection of two linked lists | Set-3 (Hashing)Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)GraphGraph and its representationsBreadth First Search or BFS for a GraphDepth First Search or DFS for a GraphDetect Cycle in a Directed GraphDetect cycle in an undirected graphDetect Cycle in a directed graph using colorsTopological SortingAll Topological Sorts of a Directed Acyclic GraphKahn’s algorithm for Topological SortingMatrixRotate Matrix ElementsInplace rotate square matrix by 90 degrees | Set 1Rotate a matrix by 90 degree without using any extra space | Set 2Rotate a Matrix by 180 degreeRotate each ring of matrix anticlockwise by K elementsTurn an image by 90 degreeCheck if all rows of a matrix are circular rotations of each otherSort the given matrixFind the row with maximum number of 1sFind median in row wise sorted matrixAdvanced Data StructureMemory efficient doubly linked listXOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2Memory efficient doubly linked listXOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
Introduction to Arrays
Arrays in C/C++
Arrays in Java
Program for array rotation
Reversal algorithm for array rotation
Block swap algorithm for array rotation
Rearrange an array such that arr[i] = i
Write a program to reverse an array or string
Rearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < i
Linked List | Set 1 (Introduction)
Linked List vs Array
Linked List | Set 2 (Inserting a node)
Linked List | Set 3 (Deleting a node)
Delete a Linked List node at a given position
Circular Linked List | Set 1 (Introduction and Applications)
Circular Linked List | Set 2 (Traversal)
Split a Circular Linked List into two halves
Sorted insert for circular linked list
Stack Data Structure (Introduction and Program)
Stack in C++ STL
Stack Class in Java
Stack in Python
C# Stack with Examples
Queue using Stacks
Design and Implement Special Stack Data Structure | Added Space Optimized Version
Implement two stacks in an array
Implement Stack using Queues
Queue | Set 1 (Introduction and Array Implementation)
Applications of Queue Data Structure
Priority Queue | Set 1 (Introduction)
Applications of Priority Queue
Deque | Set 1 (Introduction and Applications)
LRU Cache Implementation
Queue – Linked List Implementation
Binary Tree | Set 1 (Introduction)
Binary Tree | Set 2 (Properties)
Binary Tree | Set 3 (Types of Binary Tree)
Tree Traversals (Inorder, Preorder and Postorder)
Inorder Tree Traversal without Recursion
Inorder Tree Traversal without recursion and without stack!
Construct Tree from given Inorder and Preorder traversals
Construct a tree from Inorder and Level order traversals | Set 1
Construct Complete Binary Tree from its Linked List Representation
Binary Search Tree | Set 1 (Search and Insertion)
Binary Search Tree | Set 2 (Delete)
Advantages of BST over Hash Table
Construct BST from given preorder traversal | Set 1
Construct BST from given preorder traversal | Set 2
Binary Tree to Binary Search Tree Conversion
Sorted Linked List to Balanced BST
Sorted Array to Balanced BST
Find the node with minimum value in a Binary Search Tree
Binary Heap
Time Complexity of building a heap
Applications of Heap Data Structure
Binomial Heap
Fibonacci Heap | Set 1 (Introduction)
Leftist Tree / Leftist Heap
K-ary Heap
HeapSort
Iterative HeapSort
Hashing | Set 1 (Introduction)
Index Mapping (or Trivial Hashing) with negatives allowed
Hashing | Set 2 (Separate Chaining)
Hashing | Set 3 (Open Addressing)
Double Hashing
Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
Find whether an array is subset of another array | Added Method 5
Union and Intersection of two linked lists | Set-3 (Hashing)
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Graph and its representations
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Detect Cycle in a Directed Graph
Detect cycle in an undirected graph
Detect Cycle in a directed graph using colors
Topological Sorting
All Topological Sorts of a Directed Acyclic Graph
Kahn’s algorithm for Topological Sorting
Rotate Matrix Elements
Inplace rotate square matrix by 90 degrees | Set 1
Rotate a matrix by 90 degree without using any extra space | Set 2
Rotate a Matrix by 180 degree
Rotate each ring of matrix anticlockwise by K elements
Turn an image by 90 degree
Check if all rows of a matrix are circular rotations of each other
Sort the given matrix
Find the row with maximum number of 1s
Find median in row wise sorted matrix
Memory efficient doubly linked list
XOR Linked List – A Memory Efficient Doubly Linked List | Set 1
XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
Memory efficient doubly linked list
XOR Linked List – A Memory Efficient Doubly Linked List | Set 1
XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
Difficulty Level :
Hard
How to implement LRU caching scheme? What data structures should be used? We are given the total possible page numbers that can be referred. We are also given 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. Please see the Galvin book for more details (see the LRU page replacement slide here).
We use two data structures to implement an LRU Cache.  
Queue is implemented using a doubly-linked list. The maximum size of the queue will be equal to the total number of frames available (cache size). The most recently used pages will be near the front end and the least recently pages will be near the rear end.A Hash with page number as key and address of the corresponding queue node as value.
Queue is implemented using a doubly-linked list. The maximum size of the queue will be equal to the total number of frames available (cache size). The most recently used pages will be near the front end and the least recently pages will be near the rear end.
A Hash with page number as key and address of the corresponding queue node as value.
When a page is referenced, the required page may be in the memory. If it is in the memory, we need to detach the node of the list and bring it to the front of the queue. If the required page is not in memory, we bring that in memory. In simple words, we add a new node to the front of the queue and update the corresponding node address in the hash. If the queue is full, i.e. all the frames are full, we remove a node from the rear of the queue, and add the new node to the front of the queue.
Example – Consider the following reference string :  
1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5
Find the number of page faults using the least recently used (LRU) page replacement algorithm with 3-page frames. 
Explanation – 
 
Note: Initially no page is in the memory.
C++
C
Java
// We can use stl container list as a double// ended queue to store the cache keys, with// the descending time of reference from front// to back and a set container to check presence// of a key. But to fetch the address of the key// in the list using find(), it takes O(N) time.// This can be optimized by storing a reference//     (iterator) to each key in a hash map.#include <bits/stdc++.h>using namespace std;  class LRUCache {    // store keys of cache    list<int> dq;      // store references of key in cache    unordered_map<int, list<int>::iterator> ma;    int csize; // maximum capacity of cache  public:    LRUCache(int);    void refer(int);    void display();};  // Declare the sizeLRUCache::LRUCache(int n){    csize = n;}  // Refers key x with in the LRU cachevoid LRUCache::refer(int x){    // not present in cache    if (ma.find(x) == ma.end()) {        // cache is full        if (dq.size() == csize) {            // delete least recently used element            int last = dq.back();              // Pops the last element            dq.pop_back();              // Erase the last            ma.erase(last);        }    }      // present in cache    else        dq.erase(ma[x]);      // update reference    dq.push_front(x);    ma[x] = dq.begin();}  // Function to display contents of cachevoid LRUCache::display(){      // Iterate in the deque and print    // all the elements in it    for (auto it = dq.begin(); it != dq.end();         it++)        cout << (*it) << " ";      cout << endl;}  // Driver Codeint main(){    LRUCache ca(4);      ca.refer(1);    ca.refer(2);    ca.refer(3);    ca.refer(1);    ca.refer(4);    ca.refer(5);    ca.display();      return 0;}// This code is contributed by Satish Srinivas
// A C program to show implementation of LRU cache#include <stdio.h>#include <stdlib.h>  // A Queue Node (Queue is implemented using Doubly Linked List)typedef struct QNode {    struct QNode *prev, *next;    unsigned pageNumber; // the page number stored in this QNode} QNode;  // A Queue (A FIFO collection of Queue Nodes)typedef struct Queue {    unsigned count; // Number of filled frames    unsigned numberOfFrames; // total number of frames    QNode *front, *rear;} Queue;  // A hash (Collection of pointers to Queue Nodes)typedef struct Hash {    int capacity; // how many pages can be there    QNode** array; // an array of queue nodes} Hash;  // A utility function to create a new Queue Node. The queue Node// will store the given 'pageNumber'QNode* newQNode(unsigned pageNumber){    // Allocate memory and assign 'pageNumber'    QNode* temp = (QNode*)malloc(sizeof(QNode));    temp->pageNumber = pageNumber;      // Initialize prev and next as NULL    temp->prev = temp->next = NULL;      return temp;}  // A utility function to create an empty Queue.// The queue can have at most 'numberOfFrames' nodesQueue* createQueue(int numberOfFrames){    Queue* queue = (Queue*)malloc(sizeof(Queue));      // The queue is empty    queue->count = 0;    queue->front = queue->rear = NULL;      // Number of frames that can be stored in memory    queue->numberOfFrames = numberOfFrames;      return queue;}  // A utility function to create an empty Hash of given capacityHash* createHash(int capacity){    // Allocate memory for hash    Hash* hash = (Hash*)malloc(sizeof(Hash));    hash->capacity = capacity;      // Create an array of pointers for referring queue nodes    hash->array = (QNode**)malloc(hash->capacity * sizeof(QNode*));      // Initialize all hash entries as empty    int i;    for (i = 0; i < hash->capacity; ++i)        hash->array[i] = NULL;      return hash;}  // A function to check if there is slot available in memoryint AreAllFramesFull(Queue* queue){    return queue->count == queue->numberOfFrames;}  // A utility function to check if queue is emptyint isQueueEmpty(Queue* queue){    return queue->rear == NULL;}  // A utility function to delete a frame from queuevoid deQueue(Queue* queue){    if (isQueueEmpty(queue))        return;      // If this is the only node in list, then change front    if (queue->front == queue->rear)        queue->front = NULL;      // Change rear and remove the previous rear    QNode* temp = queue->rear;    queue->rear = queue->rear->prev;      if (queue->rear)        queue->rear->next = NULL;      free(temp);      // decrement the number of full frames by 1    queue->count--;}  // A function to add a page with given 'pageNumber' to both queue// and hashvoid Enqueue(Queue* queue, Hash* hash, unsigned pageNumber){    // If all frames are full, remove the page at the rear    if (AreAllFramesFull(queue)) {        // remove page from hash        hash->array[queue->rear->pageNumber] = NULL;        deQueue(queue);    }      // Create a new node with given page number,    // And add the new node to the front of queue    QNode* temp = newQNode(pageNumber);    temp->next = queue->front;      // If queue is empty, change both front and rear pointers    if (isQueueEmpty(queue))        queue->rear = queue->front = temp;    else // Else change the front    {        queue->front->prev = temp;        queue->front = temp;    }      // Add page entry to hash also    hash->array[pageNumber] = temp;      // increment number of full frames    queue->count++;}  // This function is called when a page with given 'pageNumber' is referenced// from cache (or memory). There are two cases:// 1. Frame is not there in memory, we bring it in memory and add to the front// of queue// 2. Frame is there in memory, we move the frame to front of queuevoid ReferencePage(Queue* queue, Hash* hash, unsigned pageNumber){    QNode* reqPage = hash->array[pageNumber];      // the page is not in cache, bring it    if (reqPage == NULL)        Enqueue(queue, hash, pageNumber);      // page is there and not at front, change pointer    else if (reqPage != queue->front) {        // Unlink rquested page from its current location        // in queue.        reqPage->prev->next = reqPage->next;        if (reqPage->next)            reqPage->next->prev = reqPage->prev;          // If the requested page is rear, then change rear        // as this node will be moved to front        if (reqPage == queue->rear) {            queue->rear = reqPage->prev;            queue->rear->next = NULL;        }          // Put the requested page before current front        reqPage->next = queue->front;        reqPage->prev = NULL;          // Change prev of current front        reqPage->next->prev = reqPage;          // Change front to the requested page        queue->front = reqPage;    }}  // Driver program to test above functionsint main(){    // Let cache can hold 4 pages    Queue* q = createQueue(4);      // Let 10 different pages can be requested (pages to be    // referenced are numbered from 0 to 9    Hash* hash = createHash(10);      // Let us refer pages 1, 2, 3, 1, 4, 5    ReferencePage(q, hash, 1);    ReferencePage(q, hash, 2);    ReferencePage(q, hash, 3);    ReferencePage(q, hash, 1);    ReferencePage(q, hash, 4);    ReferencePage(q, hash, 5);      // Let us print cache frames after the above referenced pages    printf("%d ", q->front->pageNumber);    printf("%d ", q->front->next->pageNumber);    printf("%d ", q->front->next->next->pageNumber);    printf("%d ", q->front->next->next->next->pageNumber);      return 0;}
/* We can use Java inbuilt Deque as a double   ended queue to store the cache keys, with   the descending time of reference from front   to back and a set container to check presence   of a key. But remove a key from the Deque using   remove(), it takes O(N) time. This can be   optimized by storing a reference (iterator) to   each key in a hash map. */import java.util.Deque;import java.util.HashSet; import java.util.LinkedList; import java.util.Iterator;  public class LRUCache {      // store keys of cache    private Deque<Integer> doublyQueue;      // store references of key in cache    private HashSet<Integer> hashSet;      // maximum capacity of cache     private final int CACHE_SIZE;      LRUCache(int capacity) {        doublyQueue = new LinkedList<>();        hashSet = new HashSet<>();        CACHE_SIZE = capacity;    }      /* Refer the page within the LRU cache */    public void refer(int page) {        if (!hashSet.contains(page)) {            if (doublyQueue.size() == CACHE_SIZE) {                int last = doublyQueue.removeLast();                hashSet.remove(last);            }         }         else {/* The found page may not be always the last element, even if it's an               intermediate element that needs to be removed and added to the start               of the Queue */            doublyQueue.remove(page);        }         doublyQueue.push(page);        hashSet.add(page);    }      // display contents of cache    public void display() {        Iterator<Integer> itr = doublyQueue.iterator();        while (itr.hasNext()) {             System.out.print(itr.next() + " ");         }     }      public static void main(String[] args) {        LRUCache cache = new LRUCache(4);        cache.refer(1);        cache.refer(2);        cache.refer(3);        cache.refer(1);        cache.refer(4);        cache.refer(5);        cache.display();    }} // This code is contributed by Niraj Kumar
5 4 1 3 
Java Implementation using LinkedHashMap. The idea is to use a LinkedHashSet that maintains the insertion order of elements. This way implementation becomes short and easy.
Java
// Java program to implement LRU cache// using LinkedHashSetimport java.util.*;  class LRUCache {      Set<Integer> cache;    int capacity;      public LRUCache(int capacity)    {        this.cache = new LinkedHashSet<Integer>(capacity);        this.capacity = capacity;    }      // 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.    public boolean get(int key)    {        if (!cache.contains(key))            return false;        cache.remove(key);        cache.add(key);        return true;    }      /* Refers key x with in the LRU cache */    public void refer(int key)    {                if (get(key) == false)           put(key);    }      // displays contents of cache in Reverse Order    public void display()    {      LinkedList<Integer> list = new LinkedList<>(cache);              // The descendingIterator() method of java.util.LinkedList      // class is used to return an iterator over the elements      // in this LinkedList in reverse sequential order      Iterator<Integer> itr = list.descendingIterator();               while (itr.hasNext())            System.out.print(itr.next() + " ");    }          public void put(int key)    {                if (cache.size() == capacity) {            int firstKey = cache.iterator().next();            cache.remove(firstKey);        }          cache.add(key);    }          public static void main(String[] args)    {        LRUCache ca = new LRUCache(4);        ca.refer(1);        ca.refer(2);        ca.refer(3);        ca.refer(1);        ca.refer(4);        ca.refer(5);        ca.display();    }}
5 4 1 3 
Python implementation using OrderedDictThis article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
_Gaurav_Tiwari
spattk
MadhaviVaddepalli
Majorssn
nirajtechi
sudhanshublaze
adnanirshad158
sumitgumber28
sharanaseem
Amazon
cpp-unordered_map
MakeMyTrip
Morgan Stanley
Snapdeal
STL
Advanced Data Structure
GATE CS
Operating Systems
Queue
Morgan Stanley
Amazon
Snapdeal
MakeMyTrip
Operating Systems
Queue
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
AVL Tree | Set 1 (Insertion)
Trie | (Insert and Search)
Red-Black Tree | Set 1 (Introduction)
Introduction of B-Tree
Agents in Artificial Intelligence
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS