Skip to main content

Compute ROC AUC from a list of model scores and a list of 0 and 1 labels, without a library. For example, scores 0.1, 0.4, 0.35, 0.8 with labels 0, 0, 1, 1 give 0.75, because 3 of the 4 pairs of one positive and one negative are ranked correctly.

Coding rounds · Intermediate 3

Short answer

AUC is the chance that a random positive scores higher than a random negative. Sort by score, give each item its rank, and use (sum of positive ranks - P * (P + 1) / 2) / (P * N), where P and N count positives and negatives. Tied scores get their average rank. Cost is O(n log n).

Deeper answer

Clarify first: the scores are any real numbers where higher means more positive, the labels are 0 and 1, and both classes must be present, or AUC is undefined. Ask how ties should count. The standard answer is half a pair.

The direct definition counts pairs: for every pair of one positive and one negative, add 1 if the positive scores higher and 0.5 if they tie, then divide by P * N. That is O(P * N), good for a check but slow. The fast version sorts the scores in ascending order and assigns ranks from 1, giving tied scores the average of their ranks. Then AUC = (sum of positive ranks - P * (P + 1) / 2) / (P * N).

Test the worked example, a perfect ranking (1.0), a reversed ranking (0.0) and all equal scores (0.5), and compare the fast version with the pair count on random data with ties. Interviewers watch for ties handled wrongly, for scores turned into labels with a threshold first, and for no check that both classes exist.

What a strong answer covers

Answer it out loud in the mock interview about 3 min

Follow-ups to expect

Common mistakes

Learn it

Choosing a metric

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.