DSA interview question
An operating system has C page frames in memory. A program accesses pages in a given order. If the page is already in memory it's a hit; otherwise it's a page fault, and the page is loaded, evicting the least recently used page if all frames are full. Count the page faults. This is the LRU cache from system design, used as a simulation: a recency-ordered list plus a hash map from page to list position gives O(1) per access.
Example: pages [5, 0, 1, 3, 2, 4, 1, 0, 5], C = 4 → 8 faults.
int pageFaults(const vector<int>& pages, int capacity);
Input (pages, C) | Output | Explanation |
|---|---|---|
([5, 0, 1, 3, 2, 4, 1, 0, 5], 4) | 8 | Only the second access to 1 is a hit |
([1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5], 3) | 10 | The classic reference string |
([7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2], 4) | 6 | |
([1, 2, 1, 2], 2) | 2 | |
([1, 1, 1], 1) | 1 |
(Confirm: frames start empty; a hit refreshes the page's recency; capacity ≥ 1.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in