802. Rank pages with PageRank, including dead-end pages
Why it matters Graph ranking with PageRank still shows up in search, recommendation and citation analysis interviews.
PageRank scores a page by how often a random surfer lands on it. With probability d the surfer follows a random outgoing link; otherwise (or on a page with no outgoing links) they jump to a uniformly random page.
Write pagerank(links, n, d=0.85, iters=100). links is a list of (src, dst) edges between pages 0..n-1 (ignore duplicates and self-links). Start with r = 1/n for every page and repeat iters times:new[j] = (1 - d) / n + d * (sum over edges i -> j of r[i] / outdeg(i) + sum over dangling pages i of r[i] / n)
Return r as a float array of length n (it sums to 1).
def pagerank(links, n, d=0.85, iters=100)Example 1
Input: pagerank([(0, 1), (1, 0)], 2)
Output: [0.5, 0.5]
Example 2
Input: links = [(0, 1), (1, 2), (2, 0), (0, 2)], n = 3
Output: [0.38779, 0.214811, 0.3974]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Count each page's out-degree after removing duplicates and self-links.
Hint 2
Each iteration, push r[i] / outdeg(i) along every edge.
Hint 3
Collect the total score of dead-end pages and spread it evenly before applying d.
Common mistakes
- Dropping dangling pages, so the scores no longer sum to 1.
- Counting duplicate edges twice.
Understand the idea
Each page splits its score evenly across its outgoing links. Dead-end pages would leak score, so their score is spread over every page. The (1 - d) / n teleport term keeps the chain irreducible so one answer exists.
two pages linking to each other are symmetric, so both get 0.5.
new = (1 - d)/n + d * (link share + dangling share / n)