You are given a file system where page P0 is a special master page. It acts as the directory or index for the entire file system. Instead of standard file data, P0 stores the starting offsets (the head pointers) for every file currently stored on the disk. To read any file, the system must look up its starting page in P0 and then traverse the chain of next_page_offset pointers.
Unfortunately, P0 has been corrupted and all head pointers are lost. You are given the page table (excluding P0) as an array pages where pages[i] = [in_use, next_page_offset] represents page P(i+1). in_use is 1 if the page is active or 0 if it is free. next_page_offset is the 1-indexed page number of the next page in the file chain, or -1 if it is the end of the file (EOF).
Return a sorted list of all starting page indices that need to be restored into P0. A starting page is any in-use page that is not pointed to by the next_page_offset of any other in-use page.
Function Signature
def recover_master_page(pages: list[list[int]]) -> list[int]:
Rules
-
pages[0]
describes page P1,
pages[1]
describes P2, and so on. P0 is not in the array.
-
Only pointers stored in in-use pages count. The
next_page_offset
of a free page is stale data and is ignored, even when it names an in-use page.
-
A free page is never a starting page.
-
The in-use pages form file chains: no in-use page points to itself, and following pointers from any in-use page never loops back to a page already visited.
-
Return the starting page numbers (1-indexed) in ascending order.
Constraints
-
1 <= pages.length <= 10^5
-
pages[i][0]
is
0
or
1
-
pages[i][1]
is
-1
(EOF) or a valid 1-indexed page number, from
1
to
pages.length
-
All
next_page_offset
values for in-use pages point to valid in-use pages or are
-1
-
There is at least one in-use page
Examples
Input: pages = [[1, 3], [0, -1], [1, -1], [1, 5], [1, -1], [0, 4]]
Output: [1, 4]
The in-use pages hold two files, P1 -> P3 -> EOF and P4 -> P5 -> EOF. P6 is free, so its stale pointer to P4 is ignored and P4 is still a starting page.
Input: pages = [[1, 2], [1, 3], [1, -1]]
Output: [1]
There is a single file chain, P1 -> P2 -> P3 -> EOF. Only P1 is not referenced by any other page.
Input: pages = [[1, -1], [1, 1], [0, -1], [1, -1]]
Output: [2, 4]
P2 points to P1, so the file is P2 -> P1 -> EOF and its start is P2 even though P1 has the smaller number. P4 is a one-page file that nothing points to, and P3 is free.