Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

ML coding · Statistics in code

ROC AUC from scores, with ties

Medium · Target 20 minutes · Python and NumPy

Given real scores and binary labels (1 positive, 0 negative), return the ROC AUC: the probability that a randomly chosen positive has a higher score than a randomly chosen negative, with ties counting one half. There is at least one positive and one negative. Aim for O(n log n).

Examples

Input scores = [0.9, 0.8, 0.3, 0.1], labels = [1, 1, 0, 0]

Output 1

Every positive outranks every negative: 1.0.

Input scores = [0.5, 0.5, 0.5, 0.5], labels = [1, 0, 1, 0]

Output 0.5

All scores tied: every pair counts one half, 0.5.

Input scores = [0.1, 0.4, 0.35, 0.8], labels = [0, 0, 1, 1]

Output 0.75

Three of the four positive–negative pairs are ordered correctly: 0.75.

Constraints

  • 2 ≤ n ≤ 10⁵
  • At least one of each label
  • Checked to a relative tolerance of 10⁻⁹

Hints

Hint 1

AUC = P(score⁺ > score⁻) + ½P(score⁺ = score⁻) over all positive–negative pairs. That is the Mann–Whitney U statistic over n₊n₋.

Hint 2

Rank all scores together. Give a block of equal scores the average of the ranks it spans.

Hint 3

AUC = (sum of positive ranks − n₊(n₊ + 1)/2) / (n₊n₋), with ranks starting at 1.

Where candidates go wrong

  • Ranking with argsort(argsort(scores)), which gives tied scores different ranks depending on input order.
  • Integrating the ROC curve with the trapezium rule but stepping through tied scores one at a time, which turns a diagonal segment into a staircase.
  • Ranks starting at 0 in the formula that assumes 1.
Console⌘/Ctrl + Enter runs

Python runs in your browser with NumPy. The first run downloads the runtime, which takes a few seconds.


Why interviewers ask it

AUC is the default metric for binary classifiers, and in credit and fraud it is the metric a model is signed off on. Interviewers ask candidates to compute it without sklearn to see whether they know what it means. The probabilistic definition gets you to an O(n log n) answer; drawing the curve gets you to an O(n²) one.

The theory behind it is in the lesson Statistics coding questions: variance, AUC and rank correlation.


Keep going