Prerequisite: Page Replacement Algorithms
In operating systems that use paging for memory management, page replacement algorithm are needed to decide which page needed to be replaced when new page comes in. Whenever a new page is referred and not present in memory, page fault occurs and Operating System replaces one of the existing pages with newly needed page. Different page replacement algorithms suggest different ways to decide which page to replace. The target for all algorithms is to reduce number of page faults.
In Least Recently Used (LRU) algorithm is a Greedy algorithm where the page to be replaced is least recently used. The idea is based on locality of reference, the least recently used page is not likely
Let say the page reference string 7 0 1 2 0 3 0 4 2 3 0 3 2 . Initially we have 4 page slots empty.
Initially all slots are empty, so when 7 0 1 2 are allocated to the empty slots —> 4 Page faults
0 is already there so —> 0 Page fault.
when 3 came it will take the place of 7 because it is least recently used —>1 Page fault
0 is already in memory so —> 0 Page fault.
4 will takes place of 1 —> 1 Page Fault
Now for the further page reference string —> 0 Page fault because they are already available in the memory.

Given memory capacity (as number of pages it can hold) and a string representing pages to be referred, write a function to find number of page faults.
Let capacity be the number of pages that
memory can hold. Let set be the current
set of pages in memory.
1- Start traversing the pages.
i) If set holds less pages than capacity.
a) Insert page into the set one by one until
the size of set reaches capacity or all
page requests are processed.
b) Simultaneously maintain the recent occurred
index of each page in a map called indexes.
c) Increment page fault
ii) Else
If current page is present in set, do nothing.
Else
a) Find the page in the set that was least
recently used. We find it using index array.
We basically need to replace the page with
minimum index.
b) Replace the found page with current page.
c) Increment page faults.
d) Update index of current page.
2. Return page faults.
Below is implementation of above steps.
C++
#include<bits/stdc++.h>
using namespace std;
int pageFaults( int pages[], int n, int capacity)
{
unordered_set< int > s;
unordered_map< int , int > indexes;
int page_faults = 0;
for ( int i=0; i<n; i++)
{
if (s.size() < capacity)
{
if (s.find(pages[i])==s.end())
{
s.insert(pages[i]);
page_faults++;
}
indexes[pages[i]] = i;
}
else
{
if (s.find(pages[i]) == s.end())
{
int lru = INT_MAX, val;
for ( auto it=s.begin(); it!=s.end(); it++)
{
if (indexes[*it] < lru)
{
lru = indexes[*it];
val = *it;
}
}
s.erase(val);
s.insert(pages[i]);
page_faults++;
}
indexes[pages[i]] = i;
}
}
return page_faults;
}
int main()
{
int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
int n = sizeof (pages)/ sizeof (pages[0]);
int capacity = 4;
cout << pageFaults(pages, n, capacity);
return 0;
}
|
Java
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
class Test
{
static int pageFaults( int pages[], int n, int capacity)
{
HashSet<Integer> s = new HashSet<>(capacity);
HashMap<Integer, Integer> indexes = new HashMap<>();
int page_faults = 0 ;
for ( int i= 0 ; i<n; i++)
{
if (s.size() < capacity)
{
if (!s.contains(pages[i]))
{
s.add(pages[i]);
page_faults++;
}
indexes.put(pages[i], i);
}
else
{
if (!s.contains(pages[i]))
{
int lru = Integer.MAX_VALUE, val=Integer.MIN_VALUE;
Iterator<Integer> itr = s.iterator();
while (itr.hasNext()) {
int temp = itr.next();
if (indexes.get(temp) < lru)
{
lru = indexes.get(temp);
val = temp;
}
}
s.remove(val);
indexes.remove(val);
s.add(pages[i]);
page_faults++;
}
indexes.put(pages[i], i);
}
}
return page_faults;
}
public static void main(String args[])
{
int pages[] = { 7 , 0 , 1 , 2 , 0 , 3 , 0 , 4 , 2 , 3 , 0 , 3 , 2 };
int capacity = 4 ;
System.out.println(pageFaults(pages, pages.length, capacity));
}
}
|
Python3
def pageFaults(pages, n, capacity):
s = set ()
indexes = {}
page_faults = 0
for i in range (n):
if len (s) < capacity:
if pages[i] not in s:
s.add(pages[i])
page_faults + = 1
indexes[pages[i]] = i
else :
if pages[i] not in s:
lru = float ( 'inf' )
for page in s:
if indexes[page] < lru:
lru = indexes[page]
val = page
s.remove(val)
s.add(pages[i])
page_faults + = 1
indexes[pages[i]] = i
return page_faults
pages = [ 7 , 0 , 1 , 2 , 0 , 3 , 0 , 4 , 2 , 3 , 0 , 3 , 2 ]
n = len (pages)
capacity = 4
print (pageFaults(pages, n, capacity))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int pageFaults( int []pages,
int n, int capacity)
{
HashSet< int > s = new HashSet< int >(capacity);
Dictionary< int ,
int > indexes = new Dictionary< int ,
int >();
int page_faults = 0;
for ( int i = 0; i < n; i++)
{
if (s.Count < capacity)
{
if (!s.Contains(pages[i]))
{
s.Add(pages[i]);
page_faults++;
}
if (indexes.ContainsKey(pages[i]))
indexes[pages[i]] = i;
else
indexes.Add(pages[i], i);
}
else
{
if (!s.Contains(pages[i]))
{
int lru = int .MaxValue, val = int .MinValue;
foreach ( int itr in s)
{
int temp = itr;
if (indexes[temp] < lru)
{
lru = indexes[temp];
val = temp;
}
}
s.Remove(val);
indexes.Remove(val);
s.Add(pages[i]);
page_faults++;
}
if (indexes.ContainsKey(pages[i]))
indexes[pages[i]] = i;
else
indexes.Add(pages[i], i);
}
}
return page_faults;
}
public static void Main(String []args)
{
int []pages = {7, 0, 1, 2, 0, 3,
0, 4, 2, 3, 0, 3, 2};
int capacity = 4;
Console.WriteLine(pageFaults(pages,
pages.Length, capacity));
}
}
|
Javascript
<script>
function pageFaults(pages,n,capacity)
{
let s = new Set();
let indexes = new Map();
let page_faults = 0;
for (let i=0; i<n; i++)
{
if (s.size < capacity)
{
if (!s.has(pages[i]))
{
s.add(pages[i]);
page_faults++;
}
indexes.set(pages[i], i);
}
else
{
if (!s.has(pages[i]))
{
let lru = Number.MAX_VALUE, val=Number.MIN_VALUE;
for (let itr of s.values()) {
let temp = itr;
if (indexes.get(temp) < lru)
{
lru = indexes.get(temp);
val = temp;
}
}
s. delete (val);
indexes. delete (val);
s.add(pages[i]);
page_faults++;
}
indexes.set(pages[i], i);
}
}
return page_faults;
}
let pages=[7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2];
let capacity = 4;
document.write(pageFaults(pages, pages.length, capacity));
</script>
|
Output:
6
Complexity Analysis :
- Time Complexity : average time complexity of set and map operations is O(1) and the worst-case time complexity is O(n) but O(n) is the dominant term.
- Space Complexity : O(capacity) which is a constant and depends on the size of the input array and the size of the memory buffer.
Another approach: (Without using HashMap)
Following are the steps to solve this problem :
- Using a deque data structure, the program implements the page replacement algorithm.
- A predetermined number of pages are kept in memory by the algorithm, and they are replaced as new pages are requested.
- Using an integer array to stimulate page requests, the code keeps track the number of page faults that occur throughout the simulation.
- The deque data structure, which is built using STL in C++, is used to maintain the pages in memory.
- The total number of page faults that occurred throughout the simulation is given as output by the code.
Below is the implementation of the above approach :
C++
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int capacity = 4;
int arr[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
deque< int > q(capacity);
int count=0;
int page_faults=0;
deque< int >::iterator itr;
q.clear();
for ( int i:arr)
{
itr = find(q.begin(),q.end(),i);
if (!(itr != q.end()))
{
++page_faults;
if (q.size() == capacity)
{
q.erase(q.begin());
q.push_back(i);
}
else {
q.push_back(i);
}
}
else
{
q.erase(itr);
q.push_back(i);
}
}
cout<<page_faults;
}
|
Java
import java.util.ArrayList;
public class LRU {
public static void main(String[] args) {
int capacity = 4 ;
int arr[] = { 7 , 0 , 1 , 2 , 0 , 3 , 0 , 4 , 2 , 3 , 0 , 3 , 2 };
ArrayList<Integer> s= new ArrayList<>(capacity);
int count= 0 ;
int page_faults= 0 ;
for ( int i:arr)
{
if (!s.contains(i))
{
if (s.size()==capacity)
{
s.remove( 0 );
s.add(capacity- 1 ,i);
}
else
s.add(count,i);
page_faults++;
++count;
}
else
{
s.remove((Object)i);
s.add(s.size(),i);
}
}
System.out.println(page_faults);
}
}
|
Python3
capacity = 4
processList = [ 7 , 0 , 1 , 2 , 0 , 3 , 0 ,
4 , 2 , 3 , 0 , 3 , 2 ]
s = []
pageFaults = 0
for i in processList:
if i not in s:
if ( len (s) = = capacity):
s.remove(s[ 0 ])
s.append(i)
else :
s.append(i)
pageFaults + = 1
else :
s.remove(i)
s.append(i)
print ( "{}" . format (pageFaults))
|
C#
using System;
using System.Collections.Generic;
class LRU
{
public static void Main(String[] args)
{
int capacity = 4;
int []arr = {7, 0, 1, 2, 0, 3, 0,
4, 2, 3, 0, 3, 2};
List< int > s = new List< int >(capacity);
int count = 0;
int page_faults = 0;
foreach ( int i in arr)
{
if (!s.Contains(i))
{
if (s.Count == capacity)
{
s.RemoveAt(0);
s.Insert(capacity - 1, i);
}
else
s.Insert(count, i);
page_faults++;
++count;
}
else
{
s.Remove(i);
s.Insert(s.Count, i);
}
}
Console.WriteLine(page_faults);
}
}
|
Javascript
let capacity = 4;
let arr = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2];
let q = [];
let count = 0;
let page_faults = 0;
let itr;
q.length = 0;
for (let i of arr)
{
itr = q.indexOf(i);
if (itr == -1) {
page_faults++;
if (q.length == capacity) {
q.shift();
q.push(i);
} else {
q.push(i);
}
} else {
q.splice(itr, 1);
q.push(i);
}
}
console.log(page_faults);
|
Output:
6
Complexity Analysis :
- Time Complexity : O(n), as it performs a constant amount of work for each page request.
- Space Complexity : O(n+4), where n is the size of the input array and 4 is the size of the memory buffer.
Note : We can also find the number of page hits. Just have to maintain a separate count.
If the current page is already in the memory then that must be count as Page-hit.
We will discuss other Page-replacement Algorithms in further sets.
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
15 Sep, 2023
Like Article
Save Article