Code RoomCoprime pairs mobius inversion
HardPrep Room Coding #1387

Coprime pairs mobius inversion

CodingAlgorithms & data structuresSenior–Staff~35 min

Given an array of positive integers, count the number of unordered pairs (i, j) with i < j such that gcd(arr[i], arr[j]) == 1. The naive O(n^2 log) pairwise approach is too slow when the array is large but values are bounded by a modest M (e.g. M <= 10^5). Use a divisor-multiple sieve and Mobius inversion over the count of elements divisible by each d. Return the number of coprime pairs (0 for an empty or single-element array).

Implement
count_coprime_pairs(arr: list[int]) → int
Examples
in[[1,2,3,4,5]]out9
What a strong answer looks like

State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.

0:00 of about 35 min
InputExpectedGot
[[1,2,3,4,5]]9not run yetsample