How Does An Optimal Page Replacement Algorithm Work?
Let's discuss how the OPT algorithm works:
-
When a page fault occurs, the algorithm looks at the future page references.
-
It selects the page that will not be used for the longest time in the future.
-
If multiple pages have the same longest time until their next use, any one of them can be selected for replacement.
-
The selected page is replaced with the new page that caused the page fault.
The OPT algorithm guarantees the minimum number of page faults for a given sequence of page references. However, its implementation is not practical as it requires knowledge of future page references.
Example of the Optimal Page Replacement (OPT) Algorithm
To understand how the Optimal Page Replacement Algorithm works, let’s look at a simple example. Consider a scenario where a computer system has room for three pages in its memory (RAM) & we have a sequence of page requests as follows: 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1.
The OPT algorithm predicts future requests to decide which pages to replace. The key is to remove the page that will not be used for the longest period. Here’s how the pages in memory change step by step:
-
Initial State (Empty Memory):
-
Memory: [ ]
-
Incoming Page: 7
-
Action: Add page 7
-
Memory: [7]
-
Second Request:
-
Memory: [7]
-
Incoming Page: 0
-
Action: Add page 0
-
Memory: [7, 0]
-
Third Request:
-
Memory: [7, 0]
-
Incoming Page: 1
-
Action: Add page 1
-
Memory: [7, 0, 1]
-
Fourth Request (Memory Full, Replacement Needed):
-
Memory: [7, 0, 1]
-
Incoming Page: 2
-
Action: Remove page 7 (not needed until much later), add page 2
- Memory: [2, 0, 1]
As more pages are requested, the algorithm continues to evaluate which existing page in memory will be least soon needed & replaces it with the new request if the memory is full. This process helps in minimizing the number of page faults over time, which is crucial for maintaining system performance.
This step-by-step example shows how the OPT algorithm functions in a practical setting, even though it requires future knowledge of requests, which in real scenarios, would be predicted or approximated by other means.
Code Example for the Optimal Page Replacement Algorithm :
- Java
- C++
- Python
- Javascript
- C#
Java
import java.util.ArrayList;
import java.util.Scanner;
public class OptimalPageReplacement {
public static void optimalPage(int[] pages, int capacity) {
ArrayList<Integer> memory = new ArrayList<>();
int pageFaults = 0;
for (int i = 0; i < pages.length; i++) {
if (!memory.contains(pages[i])) {
if (memory.size() < capacity) {
memory.add(pages[i]);
} else {
int farthest = findFarthest(pages, memory, i);
memory.set(farthest, pages[i]);
}
pageFaults++;
}
}
System.out.println("Total Page Faults: " + pageFaults);
}
private static int findFarthest(int[] pages, ArrayList<Integer> memory, int index) {
int farthest = index;
int lastUsed = -1;
for (int i = 0; i < memory.size(); i++) {
int j;
for (j = index; j < pages.length; j++) {
if (memory.get(i) == pages[j]) {
if (j > lastUsed) {
lastUsed = j;
farthest = i;
}
break;
}
}
if (j == pages.length) return i;
}
return farthest;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of pages: ");
int numPages = scanner.nextInt();
int[] pages = new int[numPages];
System.out.print("Enter page numbers: ");
for (int i = 0; i < numPages; i++) {
pages[i] = scanner.nextInt();
}
System.out.print("Enter frame capacity: ");
int capacity = scanner.nextInt();
optimalPage(pages, capacity);
}
}

You can also try this code with Online Java Compiler
Run Code
C++
#include <iostream>
#include <vector>
#include <algorithm>
void optimalPageReplacement(std::vector<int> pages, int capacity) {
std::vector<int> memory;
int pageFaults = 0;
for (int i = 0; i < pages.size(); i++) {
auto it = std::find(memory.begin(), memory.end(), pages[i]);
if (it == memory.end()) {
if (memory.size() < capacity) {
memory.push_back(pages[i]);
} else {
int farthest = findFarthest(pages, memory, i);
memory[farthest] = pages[i];
}
pageFaults++;
}
}
std::cout << "Total Page Faults: " << pageFaults << std::endl;
}
int findFarthest(const std::vector<int>& pages, const std::vector<int>& memory, int currentIndex) {
int farthestIndex = -1;
int farthest = currentIndex;
for (int i = 0; i < memory.size(); i++) {
int j;
for (j = currentIndex; j < pages.size(); j++) {
if (memory[i] == pages[j]) {
if (j > farthest) {
farthest = j;
farthestIndex = i;
}
break;
}
}
if (j == pages.size()) return i; // If never referenced again
}
return farthestIndex;
}
int main() {
int numPages, capacity;
std::cout << "Enter number of pages: ";
std::cin >> numPages;
std::vector<int> pages(numPages);
std::cout << "Enter page numbers: ";
for (int& page : pages) {
std::cin >> page;
}
std::cout << "Enter frame capacity: ";
std::cin >> capacity;
optimalPageReplacement(pages, capacity);
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Python
def optimal_page_replacement(pages, capacity):
memory = []
page_faults = 0
for i in range(len(pages)):
if pages[i] not in memory:
if len(memory) < capacity:
memory.append(pages[i])
else:
farthest = find_farthest(pages, memory, i)
memory[farthest] = pages[i]
page_faults += 1
print("Total Page Faults:", page_faults)
def find_farthest(pages, memory, current_index):
farthest = current_index
last_used = -1
for i in range(len(memory)):
try:
index = pages[current_index:].index(memory[i]) + current_index
if index > last_used:
last_used = index
farthest = i
except ValueError:
return i # If not found, return this index
return farthest
pages = list(map(int, input("Enter page numbers: ").split()))
capacity = int(input("Enter frame capacity: "))
optimal_page_replacement(pages, capacity)

You can also try this code with Online Python Compiler
Run Code
Javascript
function optimalPageReplacement(pages, capacity) {
let memory = [];
let pageFaults = 0;
for (let i = 0; i < pages.length; i++) {
if (!memory.includes(pages[i])) {
if (memory.length < capacity) {
memory.push(pages[i]);
} else {
let farthest = findFarthest(pages, memory, i);
memory[farthest] = pages[i];
}
pageFaults++;
}
}
console.log(`Total Page Faults: ${pageFaults}`);
}
function findFarthest(pages, memory, currentIndex) {
let farthest = currentIndex;
let lastUsed = -1;
for (let i = 0; i < memory.length; i++) {
let found = false;
for (let j = currentIndex; j < pages.length; j++) {
if (memory[i] === pages[j]) {
if (j > lastUsed) {
lastUsed = j;
farthest = i;
}
found = true;
break;
}
}
if (!found) return i; // If not found in the future
}
return farthest;
}
const pages = prompt("Enter page numbers:").split(" ").map(Number);
const capacity = parseInt(prompt("Enter frame capacity:"), 10);
optimalPageReplacement(pages, capacity);

You can also try this code with Online Javascript Compiler
Run Code
C#
using System;
using System.Collections.Generic;
using System.Linq;
class OptimalPageReplacement {
public static void Main() {
Console.Write("Enter number of pages: ");
int numPages = int.Parse(Console.ReadLine());
int[] pages = new int[numPages];
Console.Write("Enter page numbers: ");
for (int i = 0; i < numPages; i++) {
pages[i] = int.Parse(Console.ReadLine());
}
Console.Write("Enter frame capacity: ");
int capacity = int.Parse(Console.ReadLine());
OptimalPage(pages, capacity);
}
public static void OptimalPage(int[] pages, int capacity) {
List<int> memory = new List<int>();
int pageFaults = 0;
for (int i = 0; i < pages.Length; i++) {
if (!memory.Contains(pages[i])) {
if (memory.Count < capacity) {
memory.Add(pages[i]);
} else {
int farthest = FindFarthest(pages, memory, i);
memory[farthest] = pages[i];
}
pageFaults++;
}
}
Console.WriteLine("Total Page Faults: " + pageFaults);
}
private static int FindFarthest(int[] pages, List<int> memory, int index) {
int farthest = index;
int lastUsed = -1;
for (int i = 0; i < memory.Count; i++) {
int j;
for (j = index; j < pages.Length; j++) {
if (memory[i] == pages[j]) {
if (j > lastUsed) {
lastUsed = j;
farthest = i;
}
break;
}
}
if (j == pages.Length) return i;
}
return farthest;
}
}
Advantages of Optimal Page Replacement Algorithms in Operating Systems :
-
Minimizes Page Faults: The primary advantage of the Optimal Page Replacement Algorithm is its unparalleled efficiency in minimizing page faults. By preemptively knowing which pages will not be needed for the longest time, OPT ensures the most effective use of available memory slots, drastically reducing the likelihood of page faults compared to other algorithms.
-
Ideal Benchmark: OPT is considered an ideal benchmark in the field of memory management. It provides a theoretical standard against which the efficiency of practical page replacement algorithms can be measured. This helps developers understand the potential performance gaps in their own algorithms and strive for improvements.
-
Optimal Decision-Making: In scenarios where future page requests are known or can be accurately predicted, OPT makes flawless decisions about which pages to evict from memory. This characteristic is particularly useful in controlled environments where simulations are run to optimize other aspects of system performance.
-
Useful for Algorithm Comparison: The theoretical perfection of OPT allows it to be used as a tool for comparing the effectiveness of various page replacement strategies. By understanding how far other algorithms fall short of OPT, improvements and adjustments can be more accurately targeted.
- Educational Tool: As a concept, OPT provides valuable learning opportunities for students and professionals studying computer systems. It introduces the importance of looking ahead in algorithm design and challenges learners to think about how such foresight can be approximated in practical situations.
Disadvantages of Optimal Page Replacement Algorithms in Operating Systems :
-
Impracticality: The fundamental drawback of OPT is that it relies on future knowledge of requests, making it impractical for real-world applications. No real system can predict with certainty which pages will be needed in the future, limiting the use of OPT to theoretical exploration and simulation.
-
High Computational Overhead: In simulations, calculating the optimal page to replace requires significant computational resources, particularly as the length of the page request sequence increases. This overhead can make the algorithm inefficient for systems with limited processing power.
-
Difficult to Implement: The complexity of implementing OPT in any real system is prohibitive. It involves not only predicting future requests but also maintaining and processing this information continually, which can be resource-intensive and error-prone.
-
Not Suitable for Dynamic Systems: Systems with highly variable or unpredictable access patterns cannot effectively use OPT. Since real-time systems frequently deal with dynamic changes, the inability of OPT to adapt to unexpected requests limits its practicality.
- Lacks Flexibility: Unlike more adaptive algorithms like Least Recently Used (LRU) or First-In-First-Out (FIFO), OPT does not change its behavior based on past or present data but relies solely on predicted future usage. This rigidity means it cannot respond to shifts in data access patterns that are common in actual operating environments.
Frequently Asked Questions
What makes the OPT algorithm "optimal"?
The OPT algorithm is termed "optimal" because it minimizes the number of page faults by theoretically knowing the exact future requests and choosing to evict the page that will not be needed for the longest time.
Can the OPT algorithm be used in real-time systems?
Due to its need for future knowledge of page requests, the OPT algorithm is not practical for real-time systems. It is mainly used for theoretical analysis and simulation to benchmark other page replacement strategies.
What is the principle of an optimal algorithm?
The principle of an optimal algorithm is to provide the most efficient solution to a problem, ensuring the best performance under given constraints with minimal resource usage.
Conclusion
In this article, we have learned about the Optimal Page Replacement Algorithm, an idealized strategy for managing memory in computer systems. With an example, we demonstrated how the algorithm minimizes page faults by selecting for eviction the page that will be unused for the longest period. We also discussed the advantages, such as its ability to serve as a benchmark for other algorithms, and its disadvantages, including its impracticality for real-world application due to the requirement of future knowledge.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.