Program for Least Recently Used (LRU) Page Replacement Algorithm
MediumEvict the page unused for longest
Problem
Simulate LRU page replacement: given a page reference stream and a frame capacity, count the number of page faults.
Keep recent pages; when full, kick out the one used longest ago.
The idea
Keep the pages currently in frames along with their last use time. On a miss with no free frame, evict the page whose last use is oldest and count a page fault. It is a direct simulation, so the only design question is how quickly you can find that oldest page.
The trick
- A hash map plus a doubly linked list makes each step O(1).
- Count a fault on every miss, including the initial fills.
- A hit still updates the recency.
This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.
Step 1 of 2. Here's the example — pages=[7,0,1,2,0,3,0,4], capacity=4 Values: 7, 0, 1, 2, 0, 3, 0, 4.
1cache = ordered set2for page in pages:3 if page not in cache: fault++; if full: evict least-recently-used4 mark page as most-recently-usedInput
- array
- [7, 0, 1, 2, 0, 3, 0, 4]
Output
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Example
- Input:
- pages=[7,0,1,2,0,3,0,4], capacity=4
- Output:
- 6
Practice this problem:LeetCode(opens in a new tab)GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.