Number of Perfect Pairs
Real-world version: Dial Settings That AgreeThe statement here is our own: the same inputs, outputs and technique.
A bench of dials has been trimmed, trims[i] being the trim on the i-th dial. A trim may be negative.
Two trims a and b agree when both of these hold:
- the smaller of
|a - b|and|a + b|is no more than the smaller of|a|and|b|; - the larger of
|a - b|and|a + b|is no less than the larger of|a|and|b|.
Return the number of pairs of positions i < j whose trims agree.
Examples
Example 1
- Input
- trims = [4, 7, 9, 2]
- Output
- 3
Magnitudes 2, 4, 7 and 9. The pairs that agree are 2 with 4, 4 with 7, and 7 with 9, since each larger magnitude is within double the smaller. 2 with 7, 2 with 9 and 4 with 9 all miss.
Example 2
- Input
- trims = [-8, 4, -4, 8]
- Output
- 6
Signs fall away, leaving magnitudes 8, 4, 4 and 8. Since 8 is exactly double 4, and equal magnitudes always agree, all six pairs on the bench agree.
Example 3
- Input
- trims = [0, 3]
- Output
- 0
The smaller of the two differences is 3 and the smaller magnitude is 0, so the first test fails and the only pair on the bench does not agree.
Constraints
- 2 <= trims.length <= 10^5
- -10^9 <= trims[i] <= 10^9
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def perfect_pairs(trims: list[int]) -> int:public long perfectPairs(int[] trims)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 16 test cases: 16 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Sort Transformed ArrayReal-world version: Sorted Dial ResponsesMedium
- Sum of GCD of Formed PairsReal-world version: Total Mesh Cycle of the Gear BinMedium
- Minimum Operations to Transform Array into Alternating PrimeReal-world version: Nudging Readings onto Prime ValuesMedium
- Lexicographically Smallest Negated Permutation that Sums to TargetReal-world version: Turning Numbers Over to Hit a TotalMedium