BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Linear algebra16 of 16 in topic

802. Rank pages with PageRank, including dead-end pages

MediumLinear algebra Pro

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).

Functiondef 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.

Worked example

two pages linking to each other are symmetric, so both get 0.5.

new = (1 - d)/n + d * (link share + dangling share / n)
Topics
Linear algebra
Similar questions
  • Find the main direction of your data with PCAMedium
  • Orthonormalise a set of vectors with Gram-SchmidtMedium
  • Solve least squares with an SVD pseudo-inverse that drops tiny singular valuesMedium
  • Solve a tridiagonal system in linear time with the Thomas algorithmMedium
All Linear algebra problems
Report
802 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def pagerank(links, n, d=0.85, iters=100):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS