The Wayback Machine - https://web.archive.org/web/20240926205529/https://www.geeksforgeeks.org/program-for-least-recently-used-lru-page-replacement-algorithm/
Open In App

Program for Least Recently Used (LRU) Page Replacement algorithm

Last Updated : 15 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.
 

LRU

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++




//C++ implementation of above algorithm
#include<bits/stdc++.h>
using namespace std;
  
// Function to find page faults using indexes
int pageFaults(int pages[], int n, int capacity)
{
    // To represent set of current pages. We use
    // an unordered_set so that we quickly check
    // if a page is present in set or not
    unordered_set<int> s;
  
    // To store least recently used indexes
    // of pages.
    unordered_map<int, int> indexes;
  
    // Start from initial page
    int page_faults = 0;
    for (int i=0; i<n; i++)
    {
        // Check if the set can hold more pages
        if (s.size() < capacity)
        {
            // Insert it into set if not present
            // already which represents page fault
            if (s.find(pages[i])==s.end())
            {
                s.insert(pages[i]);
  
                // increment page fault
                page_faults++;
            }
  
            // Store the recently used index of
            // each page
            indexes[pages[i]] = i;
        }
  
        // If the set is full then need to perform lru
        // i.e. remove the least recently used page
        // and insert the current page
        else
        {
            // Check if current page is not already
            // present in the set
            if (s.find(pages[i]) == s.end())
            {
                // Find the least recently used pages
                // that is present in the set
                int lru = INT_MAX, val;
                for (auto it=s.begin(); it!=s.end(); it++)
                {
                    if (indexes[*it] < lru)
                    {
                        lru = indexes[*it];
                        val = *it;
                    }
                }
  
                // Remove the indexes page
                s.erase(val);
  
                // insert the current page
                s.insert(pages[i]);
  
                // Increment page faults
                page_faults++;
            }
  
            // Update the current page index
            indexes[pages[i]] = i;
        }
    }
  
    return page_faults;
}
  
// Driver code
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




// Java implementation of above algorithm
  
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
  
class Test
{
    // Method to find page faults using indexes
    static int pageFaults(int pages[], int n, int capacity)
    {
        // To represent set of current pages. We use
        // an unordered_set so that we quickly check
        // if a page is present in set or not
        HashSet<Integer> s = new HashSet<>(capacity);
       
        // To store least recently used indexes
        // of pages.
        HashMap<Integer, Integer> indexes = new HashMap<>();
       
        // Start from initial page
        int page_faults = 0;
        for (int i=0; i<n; i++)
        {
            // Check if the set can hold more pages
            if (s.size() < capacity)
            {
                // Insert it into set if not present
                // already which represents page fault
                if (!s.contains(pages[i]))
                {
                    s.add(pages[i]);
       
                    // increment page fault
                    page_faults++;
                }
       
                // Store the recently used index of
                // each page
                indexes.put(pages[i], i);
            }
       
            // If the set is full then need to perform lru
            // i.e. remove the least recently used page
            // and insert the current page
            else
            {
                // Check if current page is not already
                // present in the set
                if (!s.contains(pages[i]))
                {
                    // Find the least recently used pages
                    // that is present in the set
                    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;
                        }
                    }
                  
                    // Remove the indexes page
                    s.remove(val);
                   //remove lru from hashmap
                   indexes.remove(val);
                    // insert the current page
                    s.add(pages[i]);
       
                    // Increment page faults
                    page_faults++;
                }
       
                // Update the current page index
                indexes.put(pages[i], i);
            }
        }
       
        return page_faults;
    }
      
    // Driver method
    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));
    }
}
// This code is contributed by Gaurav Miglani


Python3




# Python implementation of above algorithm
def pageFaults(pages, n, capacity):
  
    # To represent set of current pages. We use
    # an unordered_set so that we quickly check
    # if a page is present in set or not
    s = set()
  
    # To store least recently used indexes
    # of pages.
    indexes = {}
  
    # Start from initial page
    page_faults = 0
    for i in range(n):
  
        # Check if the set can hold more pages
        if len(s) < capacity:
  
            # Insert it into set if not present
            # already which represents page fault
            if pages[i] not in s:
                s.add(pages[i])
  
                # increment page fault
                page_faults += 1
  
            # Store the recently used index of
            # each page
            indexes[pages[i]] = i
  
        # If the set is full then need to perform lru
        # i.e. remove the least recently used page
        # and insert the current page
        else:
  
            # Check if current page is not already
            # present in the set
            if pages[i] not in s:
  
                # Find the least recently used pages
                # that is present in the set
                lru = float('inf')
                for page in s:
                    if indexes[page] < lru:
                        lru = indexes[page]
                        val = page
  
                # Remove the indexes page
                s.remove(val)
  
                # insert the current page
                s.add(pages[i])
  
                # increment page fault
                page_faults += 1
  
            # Update the current page index
            indexes[pages[i]] = i
  
    return page_faults
  
  
# Driver code
pages = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2]
n = len(pages)
capacity = 4
print(pageFaults(pages, n, capacity))
  
# This code is contributed by ishankhandelwals.


C#




// C# implementation of above algorithm
using System;
using System.Collections.Generic;
  
class GFG
{
    // Method to find page faults 
    // using indexes
    static int pageFaults(int []pages, 
                   int n, int capacity)
    {
        // To represent set of current pages. 
        // We use an unordered_set so that 
        // we quickly check if a page is 
        // present in set or not
        HashSet<int> s = new HashSet<int>(capacity);
      
        // To store least recently used indexes
        // of pages.
        Dictionary<int, 
                   int> indexes = new Dictionary<int,
                                                 int>();
      
        // Start from initial page
        int page_faults = 0;
        for (int i = 0; i < n; i++)
        {
            // Check if the set can hold more pages
            if (s.Count < capacity)
            {
                // Insert it into set if not present
                // already which represents page fault
                if (!s.Contains(pages[i]))
                {
                    s.Add(pages[i]);
      
                    // increment page fault
                    page_faults++;
                }
      
                // Store the recently used index of
                // each page
                if(indexes.ContainsKey(pages[i]))
                    indexes[pages[i]] = i;
                else
                    indexes.Add(pages[i], i);
            }
      
            // If the set is full then need to 
            // perform lru i.e. remove the least 
            // recently used page and insert
            // the current page
            else
            {
                // Check if current page is not 
                // already present in the set
                if (!s.Contains(pages[i]))
                {
                    // Find the least recently used pages
                    // that is present in the set
                    int lru = int.MaxValue, val = int.MinValue;
                                          
                    foreach (int itr in s) 
                    {
                        int temp = itr;
                        if (indexes[temp] < lru)
                        {
                            lru = indexes[temp];
                            val = temp;
                        }
                    }
                  
                    // Remove the indexes page
                    s.Remove(val);
                      
                    //remove lru from hashmap
                    indexes.Remove(val);
                      
                    // insert the current page
                    s.Add(pages[i]);
      
                    // Increment page faults
                    page_faults++;
                }
      
                // Update the current page index
                if(indexes.ContainsKey(pages[i]))
                    indexes[pages[i]] = i;
                else
                    indexes.Add(pages[i], i);
            }
        }
        return page_faults;
    }
      
    // Driver Code
    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));
    }
}
  
// This code is contributed by 29AjayKumar


Javascript




<script>
  
// JavaScript implementation of above algorithm
  
// Method to find page faults using indexes
function pageFaults(pages,n,capacity)
{
    // To represent set of current pages. We use
        // an unordered_set so that we quickly check
        // if a page is present in set or not
        let s = new Set();
         
        // To store least recently used indexes
        // of pages.
        let indexes = new Map();
         
        // Start from initial page
        let page_faults = 0;
        for (let i=0; i<n; i++)
        {
            // Check if the set can hold more pages
            if (s.size < capacity)
            {
                // Insert it into set if not present
                // already which represents page fault
                if (!s.has(pages[i]))
                {
                    s.add(pages[i]);
         
                    // increment page fault
                    page_faults++;
                }
         
                // Store the recently used index of
                // each page
                indexes.set(pages[i], i);
            }
         
            // If the set is full then need to perform lru
            // i.e. remove the least recently used page
            // and insert the current page
            else
            {
                // Check if current page is not already
                // present in the set
                if (!s.has(pages[i]))
                {
                    // Find the least recently used pages
                    // that is present in the set
                    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;
                        }
                    }
                    
                    // Remove the indexes page
                    s.delete(val);
                   //remove lru from hashmap
                   indexes.delete(val);
                    // insert the current page
                    s.add(pages[i]);
         
                    // Increment page faults
                    page_faults++;
                }
         
                // Update the current page index
                indexes.set(pages[i], i);
            }
        }
         
        return page_faults;
}
  
 // Driver method
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));
  
  
// This code is contributed by rag2127
  
</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 :

  1. Using a deque data structure, the program implements the page replacement algorithm.
  2. A predetermined number of pages are kept in memory by the algorithm, and they are replaced as new pages are requested.
  3. Using an integer array to stimulate page requests, the code keeps track the number of page faults that occur throughout the simulation.
  4. The deque data structure, which is built using STL in C++, is used to maintain the pages in memory.
  5. 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++




// C++ program for page replacement algorithms
#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)
  {
  
    // Insert it into set if not present
    // already which represents page fault
    itr = find(q.begin(),q.end(),i);
    if(!(itr != q.end()))
    {
  
      ++page_faults;
  
      // Check if the set can hold equal pages
      if(q.size() == capacity)
      {
        q.erase(q.begin());
        q.push_back(i);
      }
      else{
        q.push_back(i);
  
      }
    }
    else
    {
      // Remove the indexes page
      q.erase(itr);
  
      // insert the current page
      q.push_back(i);         
    }
  
  }
  cout<<page_faults;
}
  
// This code is contributed by Akshit Saxena


Java




// Java program for page replacement algorithms
import java.util.ArrayList;
  
public class LRU {
      
    // Driver method
    public static void main(String[] args) {
        int capacity = 4;
        int arr[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
          
        // To represent set of current pages.We use
        // an Arraylist
        ArrayList<Integer> s=new ArrayList<>(capacity);
        int count=0;
        int page_faults=0;
        for(int i:arr)
        {
            // Insert it into set if not present
            // already which represents page fault
            if(!s.contains(i))
            {
              
            // Check if the set can hold equal pages
            if(s.size()==capacity)
            {
                s.remove(0);
                s.add(capacity-1,i);
            }
            else
                s.add(count,i);
                // Increment page faults
                page_faults++;
                ++count;
          
            }
            else
            {
                // Remove the indexes page
                s.remove((Object)i);
                // insert the current page
                s.add(s.size(),i);         
            }
          
        }
        System.out.println(page_faults);
    }
}


Python3




# Python3 program for page replacement algorithm
  
# Driver code
capacity = 4 
processList = [ 7, 0, 1, 2, 0, 3, 0,
                4, 2, 3, 0, 3, 2]
                  
# List of current pages in Main Memory
s = [] 
  
pageFaults = 0
# pageHits = 0
  
for i in processList:
  
    # If i is not present in currentPages list
    if i not in s:
  
        # Check if the list can hold equal pages
        if(len(s) == capacity):
            s.remove(s[0])
            s.append(i)
  
        else:
            s.append(i)
  
        # Increment Page faults
        pageFaults +=1
  
    # If page is already there in 
    # currentPages i.e in Main
    else:
          
        # Remove previous index of current page
        s.remove(i)
  
        # Now append it, at last index
        s.append(i)
      
print("{}".format(pageFaults))
  
# This code is contributed by mahi_07


C#




// C# program for page replacement algorithms 
using System;
using System.Collections.Generic;
  
class LRU
{ 
      
    // Driver method 
    public static void Main(String[] args) 
    { 
        int capacity = 4; 
        int []arr = {7, 0, 1, 2, 0, 3, 0, 
                     4, 2, 3, 0, 3, 2}; 
          
        // To represent set of current pages.
        // We use an Arraylist 
        List<int> s = new List<int>(capacity); 
        int count = 0; 
        int page_faults = 0; 
        foreach(int i in arr) 
        { 
            // Insert it into set if not present 
            // already which represents page fault 
            if(!s.Contains(i)) 
            { 
              
            // Check if the set can hold equal pages 
            if(s.Count == capacity) 
            { 
                s.RemoveAt(0); 
                s.Insert(capacity - 1, i); 
            } 
            else
                s.Insert(count, i); 
                  
                // Increment page faults 
                page_faults++; 
                ++count; 
            } 
            else
            { 
                // Remove the indexes page 
                s.Remove(i); 
                  
                // insert the current page 
                s.Insert(s.Count, i);         
            } 
        } 
        Console.WriteLine(page_faults); 
    } 
} 
  
// This code is contributed by Rajput-Ji


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) 
{
  
  // Insert it into set if not present
  // already which represents page fault
  itr = q.indexOf(i);
  if (itr == -1) {
    page_faults++;
  
    // Check if the set can hold equal pages
    if (q.length == capacity) {
      q.shift();
      q.push(i);
    } else {
      q.push(i);
    }
  } else {
    // Remove the indexes page
    q.splice(itr, 1);
  
    // insert the current page
    q.push(i);
  }
}
  
console.log(page_faults);
  
// This code is contributed by ishankhandelwals.


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.

 



Previous Article
Next Article

Similar Reads

Implementation of Least Recently Used (LRU) page replacement algorithm using Counters
Prerequisite - Least Recently Used (LRU) Page Replacement algorithm Least Recently Used page replacement algorithm replaces the page which is not used recently. Implementation: In this article, LRU is implemented using counters, a ctime (i.e., counter) variable is used to represent the current time, it is incremented for every page of the reference
8 min read
Not Recently Used (NRU) page replacement algorithm
It is a page replacement algorithm. This algorithm removes a page at random from the lowest numbered non-empty class. Implicit in this algorithm is that it is better to remove a modified page that has not been referenced in atleast one clock tick than a clean page that is in heavy use. It is easy to understand, moderately efficient to implement and
3 min read
Difference Between LRU and FIFO Page Replacement Algorithms in Operating System
Page replacement algorithms are used in operating systems to manage memory effectively. Page replacement algorithms are essential in operating systems for efficient memory management. These algorithms select which memory pages should be changed when a new page is brought. Least Recently Used (LRU) and First-In-First-Out (FIFO) are two popular page
3 min read
Optimal Page Replacement Algorithm
Prerequisite: Page Replacement Algorithms In operating systems, 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
15+ min read
Counting Based Page Replacement Algorithm in Operating System
Counting Based Page Replacement Algorithm replaces the page based on count i.e. number of times the page is accessed in the past. If more than one page has the same count, then the page that occupied the frame first would be replaced. Page Replacement: Page Replacement is a technique of replacing a data block (frame) of Main Memory with the data bl
5 min read
Page Faults in LRU | Implementation
LRU uses the concept of paging for memory management. A 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 to and is not present in memory, the page fault occurs and the Operating System replaces one of the existing pages with a newly needed page. LRU is one suc
15 min read
Program for Page Replacement Algorithms | Set 2 (FIFO)
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 newl
10 min read
LRU Approximation (Second Chance Algorithm)
If you are not familiar with Least Recently Used Algorithm, check Least Recently Used Algorithm(Page Replacement)This algorithm is a combination of using a queue, similar to FIFO (FIFO (Page Replacement)) alongside using an array to keep track of the bits used to give the queued page a "second chance". How does the algorithm work: Set all the value
15+ min read
Second Chance (or Clock) Page Replacement Policy
Prerequisite - Page Replacement Algorithms Apart from LRU, OPT and FIFO page replacement policies, we also have the second chance/clock page replacement policy. In the Second Chance page replacement policy, the candidate pages for removal are considered in a round robin matter, and a page that has been accessed between consecutive considerations wi
15+ min read
Advantages and Disadvantages of various Page Replacement algorithms
Page Scheduling, involves many different algorithms which have their Advantages and Disadvantages. 1. First In First Out (FIFO): Advantages -It is simple and easy to understand & implement.It is efficiently used for small systemsIt does not cause more overheadsSimplicity: FIFO is a simple and easy-to-implement algorithm. It does not require com
6 min read
Belady's Anomaly in Page Replacement Algorithms
In the Operating System, process data is loaded in fixed-sized chunks and each chunk is referred to as a page. The processor loads these pages in fixed-sized chunks of memory called frames. Typically the size of each page is always equal to the frame size. A page fault occurs when a page is not found in the memory and needs to be loaded from the di
10 min read
Page Replacement Algorithms in Operating Systems
In an operating system that uses paging for memory management, a page replacement algorithm is needed to decide which page needs to be replaced when a new page comes in. Page replacement becomes necessary when a page fault occurs and no free page frames are in memory. However, another page fault would arise if the replaced page is referenced again.
8 min read
Recently Asked Interview Questions in Product Based Companies
Cracking interviews at top product-based companies can be challenging, especially with their main focus on problem-solving skills. This article compiles a comprehensive list of interview questions recently asked at leading firms such as Amazon, Microsoft, and Google. Covering a wide range of topics including mathematics, arrays, strings, dynamic pr
8 min read
LRU Cache in Python using OrderedDict
LRU (Least Recently Used) Cache discards the least recently used items first. This algorithm requires keeping track of what was used when, which is expensive if one wants to make sure the algorithm always discards the least recently used item. General implementations of this technique require keeping "age bits" for cache-lines and track the "Least
4 min read
LRU Full Form
LRU stands for Least Recently Used. The development of the LRU algorithm ended the debate and research that had been going on about page replacement algorithms in the 1960s and 1970s. LRU replaces the line in the cache that has been in the cache the longest with no reference to it. It works on the idea that the more recently used blocks are more li
2 min read
Design LRU Cache
Design a data structure for LRU Cache. It should support the following operations: get and put. get(key) - Returns the value of the given key if it exists in the cache; otherwise, returns -1.put(key, value) - Inserts or updates the key-value pair in the cache. If the cache reaches capacity, remove the least recently used item before adding the new
5 min read
Least Frequently Used (LFU) Cache Implementation
Least Frequently Used (LFU) is a caching algorithm in which the least frequently used cache block is removed whenever the cache is overflowed. In LFU we check the old page as well as the frequency of that page and if the frequency of the page is larger than the old page we cannot remove it and if all the old pages are having same frequency then tak
9 min read
Program to find the quantity after mixture replacement
Given a container that has X liters of milk. Y liters of milk is drawn out and replaced with Y liters of water. This operation is done Z times. The task is to find out the quantity of milk left in the container.Examples: Input: X = 10 liters, Y = 2 liters, Z = 2 times Output: 6.4 liters Input: X = 25 liters, Y = 6 liters, Z = 3 times Output: 10.97
4 min read
DFA of a string with at least two 0’s and at least two 1’s
Problem - Draw deterministic finite automata (DFA) of a string with at least two 0’s and at least two 1’s. The first thing that come to mind after reading this question us that we count the number of 1's and 0's. Thereafter if they both are at least 2 the string is accepted else not accepted. But we do not have any concept of memory in a DFA so we
3 min read
Count pairs (p, q) such that p occurs in array at least q times and q occurs at least p times
Given an array arr[], the task is to count unordered pairs of positive integers (p, q) such that p occurs in the array at least q times and q occurs at least p times. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 1 (1, 1) is the only valid pair. Input: arr[] = {3, 3, 2, 2, 2} Output: 2 (2, 3) and (2, 2) are the only possible pairs. Approach: The
8 min read
Minimum days to make Array elements with value at least K sum at least X
Given two integers X, K, and two arrays arr[] and R[] both consisting of N positive integers where R[i] denotes the amount by which arr[i] increases in one day, the task is to find the minimum number of days after which the sum of array elements having value greater than or equal to K becomes at least X. Examples: Input: X = 100, K = 45, arr[] = {2
9 min read
Smallest integer having at least K prime divisors with difference between each factor at least D
Given two integers D and K. The task is to find the smallest number N which has at least K prime divisors and the difference between each pair of divisors is at least D. Examples Input: D = 3, K = 2Output: 55Explanation: It is smallest number which has 4 divisors 1 and 2 prime divisors 5, 11 and their difference between any of the pair is D. Input:
7 min read
Page Table Entries in Page Table
A Page Table is a data structure used by the operating system to keep track of the mapping between virtual addresses used by a process and the corresponding physical addresses in the system's memory. A Page Table Entry (PTE) is an entry in the Page Table that stores information about a particular page of memory. Each PTE contains information such a
7 min read
Minimum number of page turns to get to a desired page
Given a book of N pages, the task is to calculate the minimum number of page turns to get to a given desired page K. We can either start turning pages from the front side of the book (i.e from page 1) or from the back side of the book (i.e page number N). Each page has two sides, front and back, except the first page, which has only back side and t
5 min read
Difference Between Page Table and Inverted Page Table
Paging is a concept for storage management in operating systems that retrieve processes from secondary storage and store them in main memory as pages. The main concept behind paging is to divide each process into pages. Frames will also be used to divide the main memory. One page of the process is to be saved in one of the memory frames. In various
5 min read
Most Frequently Used (MFU) Algorithm in Operating System
MFU Algorithm is a Page Replacement Algorithm in the Operating System that replaces the page accessed a maximum number of times in the past. If more than one page is accessed the same number of times, then the page which occupied the frame first will be replaced. Page ReplacementIt is a technique of replacing a data block (frame) of Main Memory wit
4 min read
Know Your Sorting Algorithm | Set 1 (Sorting Weapons used by Programming Languages)
Ever wondered how sort() function we use in C++/Java or sorted() in Python work internally? Here is a list of all the inbuilt sorting algorithms of different programming languages and the algorithm they use internally. C’s qsort() – QuicksortBest Case Time Complexity- O(NlogN)Average Case Time Complexity- O(NlogN)Worse Case Time Complexity- O(N2)Au
2 min read
Minimum array size after repeated replacement of even sum pair with sum
Given an array of size N. Choose a random pair of elements from the sequence such that their sum is even, delete those two elements from the sequence and insert their sum into the sequence instead in order to minimize the length of the array. Finally, print the minimum possible size of the array. Examples : Input : 88 98 1 7 3 Output : 2 By followi
6 min read
Balanced expression with replacement
Given a string that contains only the following => ‘{‘, ‘}’, ‘(‘, ‘)’, ‘[’, ‘]’. At some places there is ‘X’ in place of any bracket. Determine whether by replacing all ‘X’s with appropriate bracket, is it possible to make a valid bracket sequence. Prerequisite: Balanced Parenthesis Expression Examples: Input : S = "{(X[X])}" Output : Balanced T
13 min read
Minimize Cost with Replacement with other allowed
Given an array of n integers, we can remove one element of the array by the following operation. Operation:We select any two numbers of the array and remove the larger number, Cost including in this operation is equal to the smaller number. You have to reduce the array into a single element by performing above operations with minimum cost. Examples
3 min read
Practice Tags :