Page Faults in LRU | Practice | GeeksforGeeks

In operating systems that use paging for memory management, page replacement algorithm is needed to decide which page needs to be replaced when the new page comes in. Whenever a new page is referred and is not present in memory, the page fault occurs and Operating System replaces one of the existing pages with a newly needed page. 
Given a sequence of pages in an array pages[] of length N and memory capacity C, find the number of page faults using Least Recently Used (LRU) Algorithm. 
Note:- Before solving this example revising the OS LRU cache mechanism is recommended.
Example 1:
Input: N = 9, C = 4
pages = {5, 0, 1, 3, 2, 4, 1, 0, 5}
Output: 8
Explaination: memory allocated with 4 pages 5, 0, 1, 
3: page fault = 4
page number 2 is required, replaces LRU 5: 
page fault = 4+1 = 5
page number 4 is required, replaces LRU 0: 
page fault = 5 + 1 = 6
page number 1 is required which is already present: 
page fault = 6 + 0 = 6
page number 0 is required which replaces LRU 3: 
page fault = 6 + 1 = 7
page number 5 is required which replaces LRU 2: 
page fault = 7 + 1  = 8.
Your Task:
You do not need to read input or print anything. Your task is to complete the function pageFaults() which takes N, C and pages[] as input parameters and returns the number of page faults.
Expected Time Complexity: O(N*C)
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ N ≤ 1000
1 ≤ C ≤ 100
1 ≤ pages[i] ≤ 1000
0
milindprajapatmst192 days ago
Total Time Taken: 0.05/1.9
Time Complexity: O(n)
Space Complexity: O(n)
Approach: Doubly Linked List 
 
class Node {
public:
    int data;
    Node *prev, *next;
    Node(int data, Node* prev = nullptr, Node* next = nullptr) {
        this->data = data;
        this->prev = prev;
        this->next = next;
    }
    ~Node() { }
};

class LinkedList {
public:
    Node *head, *tail;
    Node* append(int data) {
        if (head == nullptr)
            head = tail = new Node(data);
        else {
            tail->next = new Node(data, tail);
            tail = tail->next;
        }
        return tail;
    }
    void erase(Node* node) {
        if (node->prev)
            node->prev->next = node->next;
        else
            head = node->next;
        if (node->next)
            node->next->prev = node->prev;
        else
            tail = node->prev;
        delete(node);
    }
    LinkedList() {
        this->head = this->tail = nullptr;
    }
};

class Solution {
public:
    LinkedList List;
    unordered_map<int, Node*> M;
    int pageFaults(int N, int C, int pages[]) {
        int result = N;
        for (int i = 0; i < N; i++) {
            if (M.find(pages[i]) != M.end()) {
                result--;
                List.erase(M[pages[i]]);
                M.erase(pages[i]);
            }
            if (M.size() == C) {
                M.erase(List.head->data);
                List.erase(List.head);
            }
            M[pages[i]] = List.append(pages[i]);
        }
        return result;
    }
};
+1
bhaskarmaheshwari82 weeks ago
6 th test case not working 
 
983 96 928 731 369 772 454 434 423 947 173 645 63 9 938 207 476 193 869 185 261 356 138 520 510 248 878 287 233 255 955 215 704 883 298 425 655 752 211 430 699 385 75 114 746 14 674 223 207 543 760 82.................
 
 
  int pf=0;       vector<int> vis(1000,-1);       vector<int> m(C);       int j=0;       int k=0;       for(int i=0;i<n;i++)       {           if(k<C&&vis[arr[i]]==-1)           {               vis[arr[i]]=1;               pf++;                             m[k++]=arr[i];              //  cout<<m[k-1]<<endl;           }           else if(vis[arr[i]]==-1)           {               vis[arr[i]]=1;               vis[m[j]]=-1;               swap(arr[i],m[j]);               pf++;               j++;           }           if(j%C==0)           j=0;       }       return pf;
 
Help??
0
bhaskarmaheshwari8
This comment was deleted.
0
himanshu0719cse193 weeks ago
    static int pageFaults(int n, int c, int page[]){       LinkedList<Integer>list=new LinkedList<>();       int i=0;       int f=0;       while(i<n)       {           if(list.size()<c)           {               if(!list.contains(page[i]))               {                   list.add(page[i]);                   f++;               }               else               {                   Integer e=page[i];                   list.remove(e);                   list.add(e);               }           }           else           {               if(!list.contains(page[i]))               {                   list.pollFirst();                   f++;                   list.add(page[i]);               }               else               {                   Integer e=page[i];                   list.remove(e);                   list.add(e);               }           }           i++;       }       return f;   }
0
mrigankabhadra443 weeks ago
// Simple solution in Java
 
import java.util.LinkedList;import java.util.Queue;public class Main {    public static int pageFaults(int[] pages, int capacity) {        Queue<Integer> queue = new LinkedList<>();        int count = 0;        for (int i = 0; i < pages.length; i++) {            if (!queue.contains(pages[i])) {                if (queue.size() == capacity) {                    queue.remove();                }                queue.add(pages[i]);                count++;            }            else {                queue.remove(pages[i]);                queue.add(pages[i]);            }        }        return count;    }    public static void main(String[] args) {        int[] pages = { 1, 2, 1, 4, 2, 3, 5 };        int n = 7, c = 3;        System.out.println(pageFaults(pages, c));    }} 
0
ui19co614 weeks ago
Time - 0.0sec
 
// { Driver Code Starts// Initial Template for C++
 
#include <bits/stdc++.h>using namespace std;
// } Driver Code Ends// User function Template for C++
class Solution{   list<int>dq;   unordered_map<int ,list<int>::iterator> mp;public:   int ans=0;   void refer(int x ,int c){       if(mp.find(x)==mp.end()){           if(dq.size()==c){               mp.erase((int)dq.back());               dq.pop_back();           }           ans++;           dq.push_front(x);           mp[x]=dq.begin();       }       else{           dq.erase(mp[x]);           dq.push_front(x);           mp[x]=dq.begin();       }   }   int pageFaults(int N, int C, int pages[]){       for(int i=0;i<N;i++){           refer(pages[i],C);       }       return ans;   }};
 
+1
gaurabhkumarjha271020011 month ago
// simple algo.
// check ele. present in vector or not.
// if present so, erase
// else fault++;
// and pushback in vector. 
// in c++.  
    int faults=0;
      vector<int>v;
      
    for(int i=0;i<N;i++){
      auto it=find(v.begin(),v.end(),pages[i]);
      
      if(it==v.end()){
          
          if(v.size()==C)
          v.erase(v.begin());
       
        faults++;
      }
      else
        v.erase(it);
       
      v.push_back(pages[i]);
     }
    return faults;
0
ashutoshrastogi2 months ago
Easy Java Code
 
class Solution{
    static int pageFaults(int n, int c, int []arr){
        int i,k;
        
        int res = 0;

        ArrayList<Integer> a = new ArrayList<>();
        for(i=0;i<n;i++){
            int no = a.size();
            //System.out.println(no);
            for(k=0;k<no;k++){
                if(a.get(k)==arr[i]){
                    a.remove(k);
                    break;
                }
            }
            
            if(k!=no)
                a.add(arr[i]);
            else if(no<c){
                a.add(arr[i]);
                res++;
            }
            else{
                a.remove(0);
                a.add(arr[i]);
                res++;
            }
        }
        return res;
    }
}
+1
aloksinghbais022 months ago
C++ solution having time complexity as O(N*log(C)) and space complexity as O(N) is as follows :- 
 
Execution Time :- 0.1 / 1.9 sec
 
int pageFaults(int N, int C, int pages[]){       unordered_map<int,int> priority;       set<pair<int,int>> s;       int pgf = 0;       int pr = 1;       for(int i = 0; i < N; i++){           if(s.size() < C){               if(priority[pages[i]] != 0){                   auto it = s.find({priority[pages[i]],pages[i]});                   s.erase(it);                   priority[pages[i]] = pr++;                   s.insert({priority[pages[i]],pages[i]});               }               else{                   pgf++;                   priority[pages[i]] = pr++;                   s.insert({priority[pages[i]],pages[i]});               }           }           else{               if(priority[pages[i]] != 0){                   auto it = s.find({priority[pages[i]],pages[i]});                   s.erase(it);                   priority[pages[i]] = pr++;                   s.insert({priority[pages[i]],pages[i]});               }               else{                   pgf++;                   auto it = s.begin();                   s.erase(it);                   priority[it->second] = 0;                   priority[pages[i]] = pr++;                   s.insert({priority[pages[i]],pages[i]});               }           }       }              return (pgf);   }
+2
vaibhavank183 months ago
If your get wrong answer at this test case.

983
96 928 731 369 772 454 434 423 947 173 645 63 9 938 207 476 193 869 185 261 356 138 520 510 248 878 287 233 255 955 215 704 883 298 425 655 752 211 430 699 385 75 114 746 14 674 223..................

Then make sure you are checking that the page is not present in cache also when size of cache is less then capacity.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.